Interview question (JavaScript): “In what order do these console.logs appear—and why?” If you’ve ever been asked about the Event Loop, this is one of the most common traps: mixing sync code, async/await, Promises (microtasks) and setTimeout(0) (macrotasks). console.log("A"); setTimeout(() => console.log("B"), 0); Promise.resolve().then(() => console.log("C")); (async function run() { console.log("D"); await null; console.log("E"); })(); console.log("F"); 🧠 Predict the output order Most people guess something like: A, B, C, D, E, F — but that’s not how JS schedules work. ✅ Correct order A → D → F → C → E → B Why that happens (step-by-step) Think of JS execution like 3 lanes: 1) Call Stack (sync runs now) - A prints immediately - the async function starts immediately → prints D - await null pauses the async function and schedules the continuation as a microtask - F prints immediately 2) Microtask Queue (high priority) — drained completely - Promise.then(...) is a microtask → prints C - the await continuation resumes → prints E 3) Macrotask Queue (task queue) — one per tick setTimeout(..., 0) runs later → prints B Visual mental model If you can explain this clearly in an interview, you’re basically demonstrating: Event loop understanding + async scheduling + debugging intuition. #JavaScript #TypeScript #Frontend #WebDevelopment #SoftwareEngineering #InterviewPrep #TechInterviews #EventLoop #AsyncAwait #Promises #ReactJS #NodeJS #EngineeringLeadership #CleanCode #ProgrammingTips
JavaScript Event Loop: Sync, Async, and Micro/Macrotasks Explained
More Relevant Posts
-
🤔 Ever shipped a bug because you thought await makes things run “in parallel”… but two requests still happened one after another? 🧠 JavaScript interview question What is async/await and how is it different from Promises? ✅ Short answer • async/await is syntax on top of Promises (same async model) • async functions always return a Promise • await pauses only that async function, not the whole thread • Error handling becomes normal try/catch instead of .catch() 🔍 The real difference (what interviewers want) Promises are the mechanism. async/await is the cleaner way to write the same thing. But… await can accidentally serialize work: • await inside a loop = often slower (one-by-one) • Starting promises first, then await Promise.all() = parallel (together) 💻 Example: same task, very different performance // ❌ Sequential (one-by-one) async function loadSequential(urls) { const results = []; for (const url of urls) { const res = await fetch(url); results.push(await res.json()); } return results; } // ✅ Parallel (start all, then await together) async function loadParallel(urls) { const promises = urls.map((url) => fetch(url).then((r) => r.json())); return Promise.all(promises); } ⚠️ Common misconceptions • “await blocks the thread” → nope, it yields back to the event loop • “async returns a value” → it returns a Promise of that value • “await replaces Promise.all” → not for parallel work ⚛️ React mini-connection Inside useEffect, you can’t make the callback async, so do this: useEffect(() => { (async () => { const data = await fetch("/api/items").then(r => r.json()); setItems(data); })(); }, []); #javascript #webdevelopment #frontend #reactjs #asyncawait #promises #interviewprep #softwareengineering
To view or add a comment, sign in
-
🚀 “What Are the Different Types of Functions in JavaScript?” It sounds like a basic question. But in senior interviews, it’s rarely about listing syntax. It’s about whether you understand how functions define JavaScript’s architecture. Here’s how I would break it down in a real interview 👇 🔹 Regular (Named) Functions "function greet() {}" They’re hoisted, reusable, and show up clearly in stack traces. Ideal for utility logic and shared modules. 🔹 Function Expressions "const greet = function() {}" Not hoisted like declarations. Often used in closures and callbacks where execution order matters. 🔹 Arrow Functions "() => {}" Not just shorter syntax. They don’t bind their own "this". That makes them powerful in React components, event handlers, and async flows where lexical "this" avoids common bugs. 🔹 Higher-Order Functions Functions that accept or return other functions. Examples: "map", "filter", "reduce", middleware, custom hooks. This is where JavaScript leans into functional programming. 🔹 Callback Functions Functions passed to other functions for later execution. They power async patterns — from traditional callbacks to Promises and async/await. 🔹 Pure Functions Same input → same output. No side effects. Crucial in reducers, memoization, and predictable state management. 🔹 IIFE (Immediately Invoked Function Expression) "(function(){})()" Historically used for scope isolation before ES6 modules existed. 🔹 Curried Functions Functions returning functions: "add(2)(3)" Used for partial application and reusable, composable logic. 🔹 Constructor Functions Used with "new" to create instances before ES6 classes. They introduced prototype-based inheritance. 🔹 Generator Functions "function*" Pause and resume execution with "yield". Useful for custom iterators and controlled async flows. 💬 Interview insight Don’t stop at naming types. Connect them to real use cases: state management, async control, performance, architecture decisions. That’s what turns a simple question into a senior-level discussion. 👉 Follow Rahul R Jain for more real interview insights, React fundamentals, and practical frontend engineering content. #JavaScript #JSInterview #FrontendEngineering #WebDevelopment #AsyncProgramming #FunctionalProgramming #ReactJS #SoftwareEngineering #TechInterviews
To view or add a comment, sign in
-
Day 19/50 – JavaScript Interview Question? Question: What is the difference between synchronous and asynchronous code? Simple Answer: Synchronous code executes line by line, blocking subsequent code until the current operation completes. Asynchronous code allows other operations to run while waiting for long-running tasks (like API calls) to complete. 🧠 Why it matters in real projects: Asynchronous code prevents UI freezing during network requests, file operations, or heavy computations. Modern web apps rely heavily on async patterns (Promises, async/await) to maintain responsive user interfaces while handling background tasks. 💡 One common mistake: Forgetting to use await with async functions, causing code to continue executing before the promise resolves, leading to undefined values or race conditions. 📌 Bonus: // Synchronous - blocks execution console.log('1'); const result = expensiveOperation(); // Everything waits console.log('2'); console.log(result); // Asynchronous - non-blocking console.log('1'); fetch('/api/data').then(result => { console.log(result); // Executes later }); console.log('2'); // Doesn't wait for fetch // async/await - cleaner async code async function getData() { console.log('1'); const result = await fetch('/api/data'); // Waits here console.log(result); console.log('2'); } // Common mistake async function wrong() { const data = fetch('/api/data'); // Missing await! console.log(data); // Promise object, not the data } #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
Day 26/50 – JavaScript Interview Question? Question: What is currying in JavaScript? Simple Answer: Currying transforms a function that takes multiple arguments into a sequence of functions, each taking a single argument. Instead of add(a, b), you get add(a)(b). 🧠 Why it matters in real projects: Currying enables partial application, function composition, and more reusable code. It's fundamental to functional programming libraries like Ramda and is used in Redux middleware, event handlers, and configuration functions. 💡 One common mistake: Over-currying simple functions where it adds complexity without benefit. Use currying when you need partial application or composition, not everywhere. 📌 Bonus: // Regular function function add(a, b, c) { return a + b + c; } add(1, 2, 3); // 6 // Curried version function curriedAdd(a) { return function(b) { return function(c) { return a + b + c; }; }; } curriedAdd(1)(2)(3); // 6 // Practical use: Partial application const add5 = curriedAdd(5); const add5and10 = add5(10); console.log(add5and10(3)); // 18 // Generic curry function function curry(fn) { return function curried(...args) { if (args.length >= fn.length) { return fn.apply(this, args); } return function(...nextArgs) { return curried.apply(this, [...args, ...nextArgs]); }; }; } // Usage const multiply = (a, b, c) => a * b * c; const curriedMultiply = curry(multiply); curriedMultiply(2)(3)(4); // 24 curriedMultiply(2, 3)(4); // 24 - flexible! #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #FunctionalProgramming #Currying #WebDev #InterviewPrep
To view or add a comment, sign in
-
"The Event Loop: More Than Just A Buzzword 😎" Think you know JavaScript's event loop? Many developers stumble when asked this deceptively simple question in interviews. Why are interviewers so obsessed with it? Because understanding the event loop isn't just academic—it's a litmus test for knowing how JavaScript really works under the hood. Here's where most go wrong: they spit out the textbook definition and stop there. Vanilla definitions are not what hiring managers remember. Right answer? Dive into its real-world application: - How does it impact rendering performance? 🚀 - What happens when you misuse setTimeout in a loop? - How can you leverage the event loop to write snappier UI? Just like React is more than state hooks, the event loop is more than microtasks and macrotasks. Prove you get it. Next time you're prepping, think about: - Where does Node.js event loop differ from the browser? - Why would choosing the right async pattern save you a headache? Don't let the usual suspects get you. Be the one who stands out by connecting concepts with code. What's the toughest JavaScript question you've faced? #interviewprep #javascript #frontend #developers
To view or add a comment, sign in
-
📌 146 React.js Interview Questions & Answers – Complete Frontend Preparation Guide A comprehensive React interview reference covering fundamentals, JSX, Hooks, Lifecycle Methods, Redux, Context API, Routing, Performance Optimization, and Server-Side Rendering. React interview questions What this document covers: • React Fundamentals What is React & key features Real DOM vs Virtual DOM Flux architecture Unidirectional data flow Limitations of React • JSX & Rendering What is JSX How browsers read JSX (Babel) Rendering flow & reconciliation Mounting, Updating & Unmounting phases React vs ReactDOM • Components & Architecture Functional vs Class components Stateless components Presentational vs Container components Props & State differences Controlled vs Uncontrolled components Lifting State Up • Hooks (Core & Advanced) useState useEffect & cleanup function useContext useReducer useRef useCallback useMemo useLayoutEffect useImperativeHandle useDebugValue Custom Hooks • Lifecycle Methods componentDidMount shouldComponentUpdate componentDidUpdate componentWillUnmount Error Boundaries • Lists, Keys & Fragments Importance of key attribute React Fragments Why fragments over extra divs • Event Handling & Forms Synthetic Events HTML vs React event handling Controlled forms preventDefault usage • Routing & Navigation React Router Key prop significance in routing Code splitting • State Management Redux core principles Store, Actions, Reducers Redux Thunk Redux Saga Middleware React Context vs Redux • Performance Optimization Memoization (React.memo, useMemo) useCallback Lazy loading Reconciliation process shouldComponentUpdate • Testing & Debugging Jest framework React Developer Tools ReactTestUtils • Advanced Concepts Portals Suspense & SuspenseList Server-Side Rendering (SSR) forwardRef dangerouslySetInnerHTML node_modules & react-scripts Default port configuration A complete end-to-end React.js interview handbook designed for frontend developers preparing for product-based and enterprise-level technical interviews. I’ll continue sharing high-value interview and reference content. 🔗 Follow me: https://lnkd.in/gAJ9-6w3 — Aravind Kumar Bysani #ReactJS #FrontendDevelopment #JavaScript #Redux #ReactHooks #WebDevelopment #SoftwareEngineering #InterviewPreparation #UIDevelopment #Coding
To view or add a comment, sign in
-
Currently revising React concepts, and this post is a great resource. It covers key areas that every frontend developer should be comfortable with — especially Hooks, component lifecycle, performance optimization, and state management. Reposting for future reference and for others preparing for interviews. #React#InterviewPreparation #FrontendDeveloper#Learning
"System Engineer at TCS| Experienced QA Manual & Automation Engineer | Expertise in Design of Test Approach, Test cases & Test execution, Test Scripts Agile | Banking Domain Expertise | Delivering Quality with precision"
📌 146 React.js Interview Questions & Answers – Complete Frontend Preparation Guide A comprehensive React interview reference covering fundamentals, JSX, Hooks, Lifecycle Methods, Redux, Context API, Routing, Performance Optimization, and Server-Side Rendering. React interview questions What this document covers: • React Fundamentals What is React & key features Real DOM vs Virtual DOM Flux architecture Unidirectional data flow Limitations of React • JSX & Rendering What is JSX How browsers read JSX (Babel) Rendering flow & reconciliation Mounting, Updating & Unmounting phases React vs ReactDOM • Components & Architecture Functional vs Class components Stateless components Presentational vs Container components Props & State differences Controlled vs Uncontrolled components Lifting State Up • Hooks (Core & Advanced) useState useEffect & cleanup function useContext useReducer useRef useCallback useMemo useLayoutEffect useImperativeHandle useDebugValue Custom Hooks • Lifecycle Methods componentDidMount shouldComponentUpdate componentDidUpdate componentWillUnmount Error Boundaries • Lists, Keys & Fragments Importance of key attribute React Fragments Why fragments over extra divs • Event Handling & Forms Synthetic Events HTML vs React event handling Controlled forms preventDefault usage • Routing & Navigation React Router Key prop significance in routing Code splitting • State Management Redux core principles Store, Actions, Reducers Redux Thunk Redux Saga Middleware React Context vs Redux • Performance Optimization Memoization (React.memo, useMemo) useCallback Lazy loading Reconciliation process shouldComponentUpdate • Testing & Debugging Jest framework React Developer Tools ReactTestUtils • Advanced Concepts Portals Suspense & SuspenseList Server-Side Rendering (SSR) forwardRef dangerouslySetInnerHTML node_modules & react-scripts Default port configuration A complete end-to-end React.js interview handbook designed for frontend developers preparing for product-based and enterprise-level technical interviews. I’ll continue sharing high-value interview and reference content. 🔗 Follow me: https://lnkd.in/gAJ9-6w3 — Aravind Kumar Bysani #ReactJS #FrontendDevelopment #JavaScript #Redux #ReactHooks #WebDevelopment #SoftwareEngineering #InterviewPreparation #UIDevelopment #Coding
To view or add a comment, sign in
-
Day 28/50 – JavaScript Interview Question? Question: What is destructuring in JavaScript? Simple Answer: Destructuring is a syntax that unpacks values from arrays or properties from objects into distinct variables. It provides a concise way to extract multiple values in a single statement. 🧠 Why it matters in real projects: Destructuring makes code cleaner and more readable, especially with React props, API responses, and function parameters. It's ubiquitous in modern JavaScript and reduces boilerplate code significantly. 💡 One common mistake: Trying to destructure null or undefined, which throws an error. Always provide default values or check for existence when destructuring data from APIs or external sources. 📌 Bonus: // Array destructuring const [first, second, ...rest] = [1, 2, 3, 4, 5]; console.log(first); // 1 console.log(second); // 2 console.log(rest); // [3, 4, 5] // Object destructuring const user = { name: 'Alice', age: 30, city: 'NYC' }; const { name, age } = user; console.log(name); // "Alice" // Renaming variables const { name: userName, age: userAge } = user; // Default values (prevents undefined) const { country = 'USA' } = user; console.log(country); // "USA" // Nested destructuring const data = { user: { profile: { email: 'a@b.com' } } }; const { user: { profile: { email } } } = data; // React props destructuring function UserCard({ name, age, onDelete }) { return <div>{name}, {age}</div>; } // Function parameters function displayUser({ name, age = 18 }) { console.log(`${name} is ${age}`); } // Common mistake - destructuring undefined const { x } = null; // ✗ TypeError! const { x } = null || {}; // ✓ Safe with fallback #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #ES6 #Destructuring #WebDev #InterviewPrep
To view or add a comment, sign in
-
JavaScript Interview Question: Microtask vs Macrotask (Event Loop Deep Dive) 🧠 Q: What is the difference between Microtask Queue and Macrotask Queue in JavaScript? JavaScript uses the Event Loop to handle asynchronous operations. When async tasks complete, their callbacks are pushed into one of two queues: 1) Microtask Queue (High Priority) Includes: Promise.then() Promise.catch() queueMicrotask() MutationObserver 👉 Microtasks are executed immediately after the current synchronous code finishes, before moving to macrotasks. 2) Macrotask Queue (Lower Priority) Includes: setTimeout setInterval setImmediate (Node.js) DOM events 👉 The Event Loop executes: All synchronous code All microtasks One macrotask Repeat 📌 Important Interview Insight: Even setTimeout(fn, 0) will execute after all microtasks. 📌 This is why Promises run before setTimeout. Understanding this concept clearly separates average developers from strong frontend engineers. #JavaScript #WebDevelopment #FrontendDevelopment #SoftwareEngineering #Programming #Coding #TechCareers #Developers #MERNStack #InterviewPreparation #LearningInPublic #SoftwareDeveloper
To view or add a comment, sign in
-
Interview for Frontend(ReactJS/NextJS): Today’s interview felt like stepping into a JavaScript deep-end 😅 They went far beyond basics and drilled into core & advanced concepts: 🔹 JavaScript Core & Advanced • First-class functions • Execution context & call stack • Hoisting & TDZ • this (regular vs arrow functions) • Currying & pure vs impure functions • Debounce vs throttle • Shallow vs deep copy • undefined vs null, optional chaining, nullish coalescing • Garbage collection & weak references • Streams, backpressure & event loop • Performance: de-optimization & why deleting object properties hurts performance 🔹 Async & Architecture • Promises & async flow • Throttling vs diffusion concepts • Preventing starvation & handling concurrency 🔹 React & Frontend Fundamentals • JSX & reconciliation • Component lifecycle (exact phases) • Error boundaries & controlled vs uncontrolled components • Events in React & looping objects • useEffect behavior & optimization strategies 🔹 Next.js & Backend • Server handling in Next.js • API methods: GET, POST, PUT, DELETE • REST structure & optimization thinking 🔹 Data Structures & Problem Solving • Card stack handling approach • Step-wise optimization thinking Answered some, struggled with many, learned a LOT. Interviews like this expose gaps but also show the path forward. Back to leveling up ⚡
To view or add a comment, sign in
More from this author
Explore related topics
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