Day 50/50 – JavaScript Interview Question? Question: What is the difference between setTimeout(), setImmediate(), and process.nextTick() in Node.js? Simple Answer: setTimeout() schedules callback in macrotask queue after delay. setImmediate() executes in next event loop iteration. process.nextTick() executes before next phase (microtask, highest priority). Order: nextTick() → Promises → setImmediate() → setTimeout(). 🧠 Why it matters in real projects: Understanding these is crucial for Node.js performance, avoiding event loop starvation, and controlling async execution order. Misusing them causes performance bottlenecks or unexpected behavior. 💡 One common mistake: Overusing process.nextTick() starves the event loop since it runs before I/O. Also assuming setImmediate() runs immediately—it's actually next iteration, and order with setTimeout(0) can vary. 📌 Bonus: console.log('1: Start'); setTimeout(() => console.log('2: setTimeout'), 0); setImmediate(() => console.log('3: setImmediate')); process.nextTick(() => console.log('4: nextTick')); Promise.resolve().then(() => console.log('5: Promise')); console.log('6: End'); // Output: // 1: Start // 6: End // 4: nextTick (highest priority) // 5: Promise (microtask) // 3: setImmediate (next loop) // 2: setTimeout (timer phase) // Use cases: // nextTick - let constructor complete class AsyncResource { constructor() { process.nextTick(() => this.init()); } } // setImmediate - break up long operations function processLargeArray(arr) { const chunk = arr.splice(0, 100); processChunk(chunk); if (arr.length > 0) { setImmediate(() => processLargeArray(arr)); // ✓ Yields } } // Danger: Recursive nextTick starves I/O! function dangerous() { process.nextTick(dangerous); // ✗ Infinite, blocks I/O } // Better: use setImmediate for recursion function better() { setImmediate(better); // ✓ Allows I/O } // Modern alternative to nextTick Promise.resolve().then(() => { // Microtask like nextTick, less aggressive }); 🎉 Series Complete! 50/50 JavaScript Interview Questions #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #NodeJS #EventLoop #AsyncProgramming #WebDev #SeriesComplete
Node.js setTimeout vs setImmediate vs process.nextTick explained
More Relevant Posts
-
🚀 Day 23 of My Angular Journey – JavaScript Interview Problems (Code + Deep Dive) Today, I focused not just on solving problems, but on understanding the logic, edge cases, and performance considerations behind them. 🔹 1. Deep Clone (Object & Array) Problem: Copy nested objects without sharing references Core Logic: - Primitive → return directly - Array → recursively clone each item - Object → recursively copy keys function deepClone(obj) { if (obj === null || typeof obj !== 'object') return obj; if (Array.isArray(obj)) { return obj.map(item => deepClone(item)); } let result = {}; for (let key in obj) { result[key] = deepClone(obj[key]); } return result; } Edge Cases: - "null" (typeof null = object) - Nested arrays/objects - Circular references (needs WeakMap – advanced) Complexity: O(n) 🔹 2. Flatten Array (Recursive + Thinking) Logic: Break problem into smaller parts using recursion function flattenArray(arr) { let result = []; for (let item of arr) { if (Array.isArray(item)) { result = result.concat(flattenArray(item)); } else { result.push(item); } } return result; } Interview Twist: 👉 Can be solved using stack (iterative) instead of recursion Complexity: O(n) 🔹 3. Remove Duplicates (Optimization) Logic: Use Set for O(1) lookup function removeDuplicates(arr) { return [...new Set(arr)]; } Why better than loops? - No nested iteration - Cleaner & faster Complexity: O(n) Without Set function removeDuplicates(str) { let seen = {}; let result = ''; for (let char of str) { if (!seen[char]) { seen[char] = true; result += char; } } return result; } 🔹 4. First Non-Repeating Character Logic: - Step 1 → Count frequency - Step 2 → Find first unique function firstNonRepeating(str) { let count = {}; for (let char of str) { count[char] = (count[char] || 0) + 1; } for (let char of str) { if (count[char] === 1) return char; } return null; } Advanced Insight: 👉 Optimized using Map + Queue for real-time processing 🔹 5. Flatten Object (Real-world Application) Use Case: APIs, form data, payload transformation function flattenObject(obj, parent = '', res = {}) { for (let key in obj) { let newKey = parent ? `${parent}.${key}` : key; if (typeof obj[key] === 'object' && obj[key] !== null) { flattenObject(obj[key], newKey, res); } else { res[newKey] = obj[key]; } } return res; } Example Output: "{ user: { name: "A" } } → { "user.name": "A" }" Key Learnings from Today: ✔ Recursion to solve nested problems ✔ Stack vs recursion thinking ✔ Hashing (Map/Object) for efficient lookup ✔ Choosing right data structure (Set vs Array) ✔ Handling real-world edge cases #JavaScript #Angular #FrontendDevelopment #CodingInterview #LearningJourney
To view or add a comment, sign in
-
🚀 JavaScript Interview Questions (Must Know in 2026) Preparing for frontend interviews? Here are top JavaScript questions with clear explanations + examples 👇 🔹 1. What is ECMAScript? ECMAScript (ES) is the standard/specification on which JavaScript is based (ES6, ES7…). 👉 JS = Implementation of ECMAScript 🔹 2. Difference: var vs let vs const var → function scoped, hoisted let → block scoped, re-assignable const → block scoped, NOT re-assignable let a = 10; a = 20; // ✅ const b = 10; b = 20; // ❌ Error 🔹 3. Spread vs Rest vs Default Params Spread → expands values Rest → collects values Default → fallback values const arr = [1,2]; const newArr = [...arr, 3]; // Spread function sum(...nums) { return nums.reduce((a,b)=>a+b); } // Rest function greet(name = "Guest") { return name; } // Default 🔹 4. Deep Copy vs Shallow Copy Shallow → copies reference Deep → copies actual values const obj = {a:1}; const copy = {...obj}; // shallow 🔹 5. Promise, Callback, Async/Await Callback → function passed Promise → handles async cleanly Async/Await → syntactic sugar async function getData() { const res = await fetch(url); return res.json(); } 🔹 6. Promise vs Callback 👉 Callback → messy (callback hell) 👉 Promise → chainable, readable 🔹 7. Event Bubbling vs Capturing Bubbling → child → parent Capturing → parent → child 🔹 8. Higher Order Function Function that takes/returns another function function greet(fn){ fn(); } 🔹 9. Types of Functions Function Declaration Function Expression 🔹 10. Arrow Function Short syntax + no own this const add = (a,b) => a+b; 🔹 11. call vs apply vs bind call → args separately apply → args as array bind → returns new function 🔹 12. Ways to Create an Object Object literal {} Constructor function Class Object.create() 💡 Pro Tip: Don’t just memorize — practice + explain in interviews 🔥 Want to crack frontend interviews faster? I help developers with mock interviews + guidance 👉 Book here: https://lnkd.in/dBmB5zdi� #javascript #frontend #webdevelopment #interviewpreparation #angular #react #coding #100DaysOfCode
To view or add a comment, sign in
-
-
JavaScript Interview Preparation — Most Asked Concepts When preparing for frontend interviews, strong JavaScript fundamentals are essential. Frameworks evolve rapidly, but the core concepts of JavaScript remain constant. Here are some common areas that interviewers focus on: 1. JavaScript Basics - Primitive vs Non-Primitive data types - typeof operator - null vs undefined - NaN behavior - Dynamic typing in JavaScript These questions assess your understanding of how JavaScript operates internally. 2. ES6 Features - Arrow functions - Template literals - Destructuring - Enhanced object literals - Promises ES6 introduced powerful and cleaner features that are prevalent in modern codebases. 3. Variables & Hoisting A frequently discussed topic. Understand: - var vs let vs const - Block scope vs function scope - Hoisting behavior - Temporal Dead Zone Many developers use these concepts daily but find it challenging to explain them during interviews. 4. Functions & Execution Context Key concepts include: - Arrow functions vs traditional functions - this keyword behavior - call(), apply(), bind() A grasp of execution context demonstrates a deep understanding of JavaScript runtime behavior. 5. Functional Programming Modern JavaScript relies on: - Higher-order functions - map() - filter() - reduce() These are commonly used in frontend codebases. 6. Scope & Closures One of the most crucial JavaScript topics. Understand: - Global scope - Local scope - Scope chain - Closures Closures frequently appear in frontend interview questions. 7. Browser Concepts Frontend developers should be familiar with: - DOM (Document Object Model) - BOM (Browser Object Model) - Event handling These concepts explain how JavaScript interacts with the browser. One truth about JavaScript interviews is that while frameworks change every few years, JavaScript fundamentals remain unchanged. A strong foundation makes learning frameworks like React, Angular, or Vue much easier. Save this for your next frontend interview
To view or add a comment, sign in
-
✅ *Top JavaScript Coding Interview Questions* 🧠💻 *1️⃣ What is the difference between `==` and `===` in JavaScript?* *Answer:* - `==` compares values with type coercion. - `===` compares both value *and* type (strict equality). ```js 5 == "5" // true 5 === "5" // false ``` *2️⃣ How to check if a variable is an array?* *Answer:* ```js Array.isArray(myVar); // returns true if myVar is an array ``` *3️⃣ What is a closure in JavaScript?* *Answer:* A closure is when an inner function has access to variables from an outer function even after the outer function has returned. ```js function outer() { let count = 0; return function inner() { return ++count; } } const counter = outer(); counter(); // 1 ``` *4️⃣ Explain event delegation.* *Answer:* Event delegation is a technique of handling events at a higher-level element rather than on individual elements by using event bubbling. ```js document.getElementById("parent").addEventListener("click", (e) => { if (e.target.tagName === "BUTTON") { console.log("Button clicked:", e.target.textContent); } }); ``` *5️⃣ What is the difference between `let`, `const`, and `var`?* *Answer:* - `var`: function-scoped, hoisted - `let`: block-scoped, reassignable - `const`: block-scoped, cannot be reassigned *6️⃣ How does `this` keyword behave?* *Answer:* - In global scope: `this` refers to the global object (e.g., `window` in browsers). - In object methods: `this` refers to the object. - In arrow functions: `this` is lexically bound (takes value from surrounding context). *7️⃣ Write a function to reverse a string.* ```js function reverseStr(str) { return str.split("").reverse().join(""); } reverseStr("hello"); // "olleh" ``` *8️⃣ What is the output?* ```js console.log(typeof null); // "object" ``` *Explanation:* This is a historical bug in JavaScript and remains for backward compatibility. 💬 *React ❤️ for more!*
To view or add a comment, sign in
-
JavaScript Interview Question #2 ------------------------------------ Problem: Convert an array of key-value objects into a single object. Input: [{"key": "a", "value":1}, {"key": "b", "value": 2}] Output: {"a" : 1, "b" : 2} Solution: The input is an array of objects, and the goal is to transform it into a single object. There are multiple ways to solve this: 1. using for...of loop const arr = [{"key": "a", "value":1}, {"key": "b", "value": 2}]; let newObj = {}; for(let e of arr){ newObj[e.key] = e.value; } console.log(newObj); 2. using Object.fromEntries const arr = [{"key": "a", "value":1}, {"key": "b", "value": 2}]; const newObj = Object.fromEntries( arr.map(item => [item.key, item.value]) ); console.log(newObj); 3. using reduce() const arr = [{"key": "a", "value":1}, {"key": "b", "value": 2}]; const newObj = arr.reduce((acc, curr) => { acc[curr.key] = curr.value; return acc; }, {}); console.log(newObj); ------------------------------------------------------------------------------------- Different approaches help to build flexibility in problem-solving. I used the for...of loop in my interview. Which one do you prefer ?
To view or add a comment, sign in
-
-
*🚀 JavaScript Closures 🔥* Closures are a fundamental concept in JavaScript, often asked in interviews. A closure is when a function remembers variables from its outer scope, even after the outer function has finished executing. *🔹 1. Basic Example of Closure* function outer() { let count = 0; function inner() { count++; console.log(count); } return inner; } const counter = outer(); counter(); // 1 counter(); // 2 counter(); // 3 The inner function remembers the `count` variable even after the outer function has finished executing. *🔹 2. Why Closures Work* Because of lexical scope, inner functions can access their own variables, parent function variables, and global variables, even after the parent function ends. *🔹 3. Closures for Data Privacy (Very Important)* Closures help protect data. function createBankAccount() { let balance = 1000; return function(amount) { balance += amount; console.log(balance); } } const account = createBankAccount(); account(500); // 1500 account(200); // 1700 The `balance` variable is private and cannot be accessed directly. *🔹 4. Real-World Use Cases* Closures are used in: ✅ Data hiding / encapsulation ✅ Callbacks ✅ Event handlers ✅ setTimeout / async code ✅ Functional programming
To view or add a comment, sign in
-
*🚀 JavaScript Closures 🔥* Closures are a fundamental concept in JavaScript, often asked in interviews. A closure is when a function remembers variables from its outer scope, even after the outer function has finished executing. *🔹 1. Basic Example of Closure* function outer() { let count = 0; function inner() { count++; console.log(count); } return inner; } const counter = outer(); counter(); // 1 counter(); // 2 counter(); // 3 The inner function remembers the `count` variable even after the outer function has finished executing. *🔹 2. Why Closures Work* Because of lexical scope, inner functions can access their own variables, parent function variables, and global variables, even after the parent function ends. *🔹 3. Closures for Data Privacy (Very Important)* Closures help protect data. function createBankAccount() { let balance = 1000; return function(amount) { balance += amount; console.log(balance); } } const account = createBankAccount(); account(500); // 1500 account(200); // 1700 The `balance` variable is private and cannot be accessed directly. *🔹 4. Real-World Use Cases* Closures are used in: ✅ Data hiding / encapsulation ✅ Callbacks ✅ Event handlers ✅ setTimeout / async code ✅ Functional programming *Double Tap ❤️ For More*
To view or add a comment, sign in
-
7 JavaScript interview questions that trip up even senior devs. I've seen all of these asked in real interviews. And I've seen experienced engineers get them wrong. Not because they're bad engineers — because JavaScript is weird. Save this for your next interview prep. 1. What's the output? console.log(typeof null); Most people say "null." The answer is "object." It's a 25-year-old bug in JS that was never fixed. Interviewers love this one. 2. What gets logged? for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } Not 0, 1, 2. It's 3, 3, 3. Because var is function-scoped and by the time the timeout runs, the loop is done. Fix? Use let instead of var. 3. What's the difference between == and ===? Everyone says "== does type coercion." But can you explain WHY [] == false is true while [] is truthy? That's where it gets tricky. The real answer involves the Abstract Equality Comparison Algorithm. 4. What's the output? console.log(0.1 + 0.2 === 0.3); It's false. Floating point precision. 0.1 + 0.2 is actually 0.30000000000000004. This catches everyone at least once. 5. What does this return? function foo() { return { name: "Sanket" } } It returns undefined. Not the object. JavaScript's automatic semicolon insertion adds a semicolon after return. The object is unreachable code. 6. What's the difference between null and undefined? undefined means a variable was declared but never assigned. null means you intentionally set it to "nothing." They're different types but == says they're equal. === says they're not. 7. What's the output? const arr = [1, 2, 3]; arr[10] = 11; console.log(arr.length); It's 11. Not 4. JavaScript creates "empty slots" for indices 3-9. The array has holes. The pattern I've noticed — the questions that trip people up aren't about frameworks or patterns. They're about understanding how JavaScript actually works under the hood. If you know the quirks, you'll stand out in any interview. Which JS question tripped YOU up the hardest? Drop it below — let's build a thread of tricky ones 👇 #JavaScript #InterviewPrep #WebDevelopment #Deel #SoftwareEngineering
To view or add a comment, sign in
-
🚀 React + JavaScript Interview Questions (Beginner → Advanced) A structured list of questions I prepared while leveling up my frontend skills 👇 --- 🔥 BEGINNER (10 Q&A) • Q1: What is JavaScript? 👉 A programming language used to create dynamic web content • Q2: Difference between var, let, const? 👉 var: function scoped 👉 let/const: block scoped • Q3: What is a function? 👉 A reusable block of code • Q4: What is an array? 👉 A collection of elements • Q5: What is an object? 👉 Key-value pair structure • Q6: What is React? 👉 A library for building UI components • Q7: What is a component? 👉 Reusable UI block • Q8: What is props? 👉 Data passed from parent to child • Q9: What is state? 👉 Data managed inside a component • Q10: What is useState? 👉 Hook to manage state in functional components --- ⚡ INTERMEDIATE (10 Q&A) • Q1: What is closure? 👉 Function with access to its outer scope • Q2: What is event delegation? 👉 Handling events at parent level • Q3: What is promise? 👉 Handles async operations • Q4: What is async/await? 👉 Cleaner way to handle promises • Q5: What is useEffect? 👉 Handles side effects (API, DOM updates) • Q6: What is virtual DOM? 👉 Lightweight copy of real DOM • Q7: What is key in React? 👉 Unique identifier for list items • Q8: What is lifting state up? 👉 Sharing state via parent • Q9: What is controlled component? 👉 Form controlled by React state • Q10: What is React Router? 👉 Library for navigation in React apps --- 🚀 ADVANCED (20 Q&A) • Q1: What is event loop? 👉 Handles async execution in JS • Q2: What are call, apply, bind? 👉 Methods to control "this" • Q3: What is hoisting? 👉 Variables/functions moved to top • Q4: What is prototypal inheritance? 👉 Objects inherit from other objects • Q5: What is memoization? 👉 Caching results to improve performance • Q6: What is useMemo? 👉 Memoizes computed values • Q7: What is useCallback? 👉 Memoizes functions • Q8: What is Context API? 👉 Global state management • Q9: What are custom hooks? 👉 Reusable logic functions • Q10: What is code splitting? 👉 Load code on demand • Q11: What is lazy loading? 👉 Load components only when needed • Q12: What is reconciliation? 👉 React diffing algorithm • Q13: What are higher-order components? 👉 Functions that return components • Q14: What is debounce vs throttle? 👉 Control function execution rate • Q15: What is SSR? 👉 Server-side rendering • Q16: What is hydration? 👉 Attaching JS to server HTML • Q17: What is strict mode in React? 👉 Helps find potential issues • Q18: What is error boundary? 👉 Catch UI errors • Q19: What is React Fiber? 👉 New rendering engine • Q20: What is performance optimization in React? 👉 Using memo, lazy, proper state design --- 💡 Tip: Don’t just read — try implementing each concept in a small project 🔁 Save this for interviews #ReactJS #JavaScript #FrontendDeveloper #InterviewPrep #WebDevelopment
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development