JavaScript Event Loop:- Just wrapped up a deep dive into JavaScript's Event Loop via hands-on exercises—what a great refresher on async execution in the browser! As a frontend dev, it clarified the nuances that can trip you up in real-world code. Quick recap of the model:- Sync code runs on the call stack. Microtasks (e.g., Promise.then, queueMicrotask) drain fully before macrotasks. Macrotasks (e.g., setTimeout, DOM events) defer to the next loop cycle. Rendering waits until stack and microtasks clear. Explored chained promises, nested setTimeouts, and microtasks in macrotasks—eye-opening how they can extend loops subtly! Here are two standout examples (run them in your console or JavaScript Visualizer 9000): Example 1: Nested Promises with setTimeout. JavaScriptconsole.log('A'); setTimeout(() => { console.log('B'); Promise.resolve().then(() => console.log('C')); }, 0); Promise.resolve().then(() => { console.log('D'); setTimeout(() => console.log('E'), 0); }); console.log('F'); Output: A, F, D, B, C, E Example 2: Promise Chaining with setTimeout JavaScriptconsole.log('1'); setTimeout(() => { console.log('2'); Promise.resolve().then(() => console.log('3')).then(() => console.log('4')); }, 0); Promise.resolve().then(() => console.log('5')).then(() => console.log('6')); console.log('7'); Output: 1, 7, 5, 6, 2, 3, 4 Key takeaways: Microtasks can swell queues and delay renders—mind those chains! setTimeout(..., 0) always waits for the next loop. Long microtask runs create "long tasks," harming UX. Essential for debugging async bugs and optimizing apps. What's your top Event Loop insight? Share below! #JavaScript #EventLoop #AsyncProgramming #FrontendDevelopment #WebDev
JavaScript Event Loop: Async Execution in the Browser
More Relevant Posts
-
JavaScript Event Loop, Microtasks, and Macrotasks Event Loop Overview The event loop is JavaScript's mechanism for handling asynchronous operations. It's what enables JavaScript to be non-blocking despite being single-threaded javascript console.log('1. Start'); setTimeout(() => console.log('2. Timeout'), 0); Promise.resolve().then(() => console.log('3. Promise')); console.log('4. End'); // Output order: // 1. Start // 4. End // 3. Promise // 2. Timeout Microtasks vs Macrotasks Macrotasks (Tasks): What they are: Larger, independent tasks Examples: setTimeout, setInterval setImmediate (Node.js) I/O operations UI rendering (browser) requestAnimationFrame (browser) Queue: Macrotask Queue (Task Queue) Microtasks: What they are: Smaller, high-priority tasks Examples: Promise callbacks (.then(), .catch(), .finally()) queueMicrotask() MutationObserver (browser) process.nextTick() (Node.js - has even higher priority) Queue: Microtask Queue (Job Queue) Execution Order Rules: console.log('Script start'); setTimeout(() => { console.log('setTimeout'); }, 0); Promise.resolve() .then(() => { console.log('Promise 1'); }) .then(() => { console.log('Promise 2'); }); console.log('Script end'); /* Execution Order: 1. Script start 2. Script end 3. Promise 1 4. Promise 2 5. setTimeout */ Key Execution Flow: Execute all synchronous code Process ALL microtasks in the queue Render (if browser) Process ONE macrotask Repeat from step 2 Visualizing the Event Loop text ┌───────────────────────────┐ │ Call Stack │ └─────────────┬─────────────┘ │ ┌─────────────▼───────┐ │ Event Loop (Monitors) │ └───────────┬──────────┘ │ ┌─────────┴───── ┐ │ │ ┌───▼──┐ ┌─── ▼──┐ │ Micro │ │ Macro │ │ Tasks │ │ Tasks │ │ Queue │ │ Queue │ └───────┘ └──────── ┘ Practical Implications 1. Microtasks Block Rendering // This will freeze the UI function freezeUI() { Promise.resolve().then(() => { freezeUI(); // Infinite microtask loop }); } // freezeUI(); // Warning: Don't run this! 2. Proper Task Scheduling // ❌ Poor practice - might block UI function processHeavyData() { for (let i = 0; i < 1000000; i++) { Promise.resolve().then(() => { // Heavy computation in microtask }); } } // ✅ Better - yields to browser rendering function processHeavyDataBetter() { function chunkedProcess(start) { for (let i = start; i < start + 1000; i++) { // Process chunk } if (start < 1000000) { // Use macrotask to allow rendering setTimeout(() => chunkedProcess(start + 1000), 0); } } chunkedProcess(0); } Best Practices Use microtasks for immediate async operations // Defer non-critical work //Avoid microtask recursion
To view or add a comment, sign in
-
-
🔑 Prototype & Inheritance in JavaScript 1. Prototype Chain Every JavaScript object has a hidden property called [[Prototype]]. When you try to access a property that doesn’t exist on the object itself, JavaScript looks up the prototype chain to find it. Example: const obj = {}; console.log(obj.toString()); // found in Object.prototype 2. Constructor Functions & new When you use the new keyword, JavaScript creates a new object and links it to the constructor’s prototype. Example: function Person(name) { this.name = name; } Person.prototype.greet = function() { return `Hello, ${this.name}`; }; const varun = new Person("Varun"); console.log(varun.greet()); // Hello, Varun 3. ES6 Classes (Syntactic Sugar) JavaScript classes are just syntactic sugar over prototype-based inheritance. They make the code cleaner and more readable, but under the hood, they still use prototypes. Example: class Animal { speak() { console.log("Sound..."); } } class Dog extends Animal { speak() { console.log("Woof!"); } } new Dog().speak(); // Woof! 4. Why It’s Important Frameworks like React and Node.js rely heavily on prototype chains. Performance optimization: Adding methods to the prototype is memory-efficient. Inheritance patterns: Promotes reusability and follows the DRY (Don't Repeat Yourself) principle. 📌 Quick Interview Tip Interviewers often ask: “Explain the prototype chain.” “What’s the difference between class inheritance and prototype inheritance?” “Why are methods added to the prototype instead of inside the constructor?” const obj = {}; console.log(obj.toString()); // found in Object.prototype 2. Constructor Functions & new Jab tum new keyword use karte ho, ek naya object banata hai jo constructor ke prototype se link hota hai. Example: function Person(name) { this.name = name; } Person.prototype.greet = function() { return `Hello, ${this.name}`; }; const champ= new Person("Champ"); console.log(champ.greet()); // Hello, Champ 3. ES6 Classes (syntactic sugar) Classes JS me bas prototype-based inheritance ka cleaner syntax hain. Example: class Animal { speak() { console.log("Sound..."); } } class Dog extends Animal { speak() { console.log("Woof!"); } } new Dog().speak(); // Woof! 4. Why It’s Important Frameworks like React and Node.js rely heavily on prototype chains. Performance optimization: Adding methods to the prototype is memory-efficient. Inheritance patterns: Promotes reusability and follows the DRY (Don't Repeat Yourself) principle. #React #ReactJS #Frontend #WebDevelopment #JavaScript #Interviews #SoftwareEngineering #infy
To view or add a comment, sign in
-
🔍 JavaScript Objects: Dot Notation vs Bracket Notation Why do we have two ways to access object properties — and when should we use each? If both dot notation and bracket notation do the same thing, why does JavaScript even support both? The short answer: flexibility + real-world use cases. Let’s break it down 👇 ⸻——————————————————- 1️⃣ Dot Notation – Clean, readable, and predictable const user = { name: "Jagdish", role: "Frontend Developer" }; user.name; // "Jagdish" ——————————————- ✅ When to use dot notation • Property names are known at development time • Keys are valid JavaScript identifiers • You want clean & readable code 🚫 When you can’t use dot notation user.first-name ❌ // Error user["first-name"] ✅ Why? Dot notation does not support: • Spaces • Hyphens (-) • Dynamic values —————————————————— 2️⃣ Bracket Notation – Dynamic and powerful const key = "role"; user[key]; // "Frontend Developer" ✅ When to use bracket notation • Property name is dynamic • Key comes from user input, API response, or loop • Property contains special characters ———————————— const data = { "total-users": 120, "2025": "Active" }; data["total-users"]; // 120 data["2025"]; // "Active" —————————————- Dot notation fails here ❌ Bracket notation works perfectly ✅ _______________________________ 3️⃣ Real-world examples 🔹 API responses response.data[fieldName]; You don’t know the key beforehand → bracket notation is required. 🔹 Forms & dynamic filters filters[selectedFilter]; 🔹 Looping through objects for (let key in user) { console.log(user[key]); } Dot notation simply cannot work here. ——————————————————————- 4️⃣ Mental model to remember forever 🧠 • Dot notation → Static & known • Bracket notation → Dynamic & unknown If JavaScript needs to evaluate the key at runtime, you must use bracket notation. JavaScript didn’t give us two notations by accident. It gave us simplicity and power. Knowing why and when to use each is what separates 👉 someone who knows syntax from 👉 someone who understands JavaScript deeply. If this helped you, react or share — someone in your network needs this today 🚀 #JavaScript #FrontendDevelopment #WebDevelopment #JavaScriptTips #CodingBestPractices #LearnJavaScript #SoftwareEngineering #CleanCode #DeveloperCommunity #ProgrammingConcepts #TechCareers #ReactJS #WebDev
To view or add a comment, sign in
-
-
When I first heard about the JavaScript Event Loop, it sounded extremely complex. ☺️ Call Stack? ☺️ Callback Queue? ☺️ Web APIs? But once I understood the logic behind it, asynchronous JavaScript finally made sense. 1️⃣ JavaScript Is Single-Threaded 2️⃣ JavaScript can do one thing at a time. 3️⃣ It uses something called the Call Stack to execute functions line by line. So how does it handle: • setTimeout() • API calls • User clicks without freezing the application? This Is Where the Event Loop Comes In Behind the scenes, JavaScript uses: • Call Stack • Web APIs • Callback Queue • Event Loop Here’s the simple flow: 1️⃣ Synchronous code goes to the Call Stack. 2️⃣ Async tasks (like setTimeout or fetch) go to Web APIs. 3️⃣ Once completed, their callbacks move to the Callback Queue. 4️⃣ The Event Loop checks if the Call Stack is empty. 5️⃣ If empty, it pushes the callback into the stack for execution. ┌─────────────────┐ Call Stack (Runs code) └─────────────────┘ ↑ │ ┌─────────────────┐ Event Loop (Traffic Cop) └─────────────────┘ ↑ │ ┌─────────────────┐ Callback Queue (Waiting Tasks) └─────────────────┘ ↑ │ ┌─────────────────┐ Web APIs (Timers, Fetch) └─────────────────┘ The Event Loop is just a traffic controller. 🤦♂️Common Beginner Mistake❓ Thinking asynchronous code runs immediately. 👉Example: setTimeout(() => { console.log("Hello"); }, 0); Even with 0 delay, it waits until the Call Stack is empty.
To view or add a comment, sign in
-
-
💛 Debouncing & Throttling in JavaScript — Boost Performance Like a Pro Ever built: 👉 Search input 👉 Scroll animation 👉 Resize handler 👉 Button click spam …and your app suddenly became slow or laggy? 😵 Because events like: ▪️ scroll ▪️ resize ▪️ mousemove ▪️ keyup can fire 100+ times per second. If your API or heavy logic runs each time… 💥 Performance destroyed. That’s where Debouncing & Throttling save the day. ♦️ The Core Problem 🧠 window.addEventListener("scroll", () => { console.log("Scrolling..."); }); Scroll once → fires hundreds of times 😬 👉 Too many function calls 👉 Too many API requests 👉 UI jank We need control. ♦️ 1️⃣ Debouncing ⏳ 📌 Definition 👉 Execute function only after user stops triggering the event Think: “Wait… let them finish first” Example (Search Bar 🔍) searchInput.addEventListener("keyup", debounce(fetchResults, 500)); User types: r → ra → raj → rajk Without debounce: ❌ 4 API calls With debounce: ✅ 1 API call (after typing stops) 🧠 How It Works Every event: 👉 clears previous timer 👉 sets new timer Only last one survives. ✅ Debounce Polyfill function debounce(fn, delay) { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => { fn.apply(this, args); }, delay); }; } ✅ Real-World Use Cases ✔️ Search suggestions ✔️ Auto-save ✔️ Form validation ✔️ API calls ✔️ Resize events 👉 “Execute after user stops” ♦️ 2️⃣ Throttling 🚦 📌 Definition 👉 Execute function at most once every X milliseconds Think: “Run regularly, but limit frequency” Example (Scroll Tracking 📜) window.addEventListener("scroll", throttle(updateUI, 200)); Scrolling for 5 seconds: Without throttle: ❌ 1000+ calls With throttle: ✅ ~25 calls 🧠 How It Works 👉 First call runs 👉 Next calls ignored until delay passes ✅ Throttle Polyfill function throttle(fn, limit) { let flag = true; return function (...args) { if (!flag) return; fn.apply(this, args); flag = false; setTimeout(() => { flag = true; }, limit); }; } ✅ Real-World Use Cases ✔️ Infinite scroll ✔️ Scroll animations ✔️ Button spam prevention ✔️ Window resize ✔️ Game controls 👉 “Run at controlled intervals” ♦️ Debounce vs Throttle ⚔️ 👉 Debouncing delays execution until events stop firing 👉 Throttling limits execution to fixed intervals Both: ✔️ Reduce unnecessary calls ✔️ Improve performance ✔️ Prevent UI lag ♦️ Mental Model 🧠 Debounce: “Wait till user is done” Throttle: “Slow down the calls” 🥇 Interview One-Liner Debouncing delays execution until events stop firing, while throttling limits execution to fixed intervals — both help optimize performance for high-frequency events like scroll, resize, and input. If this helped, drop a 💛 or share 🔁 Next deep dive 👉 ( Event Propagation ) - Bubbling, Capturing, and Deligation #JavaScript #JSInternals #LearnJavaScript #WebDevelopment #ProgrammingConcepts #WebDevJourney #BuildInPublic
To view or add a comment, sign in
-
-
𝗪𝗲𝗹𝗹-𝗞𝗻𝗼𝘄𝗻 𝗦𝘆𝗺𝗯𝗼𝗹𝘀 𝗮𝗻𝗱 𝗧𝗵𝗲𝗶𝗿 𝗔𝗽𝗽𝗹𝗶𝗰𝗮𝘁𝗶𝗼𝗻𝘀 JavaScript has evolved over time. One major update was the introduction of Symbols in ECMAScript 2015. Well-Known Symbols provide a unique way to define behavior and properties in JavaScript. To understand Well-Known Symbols, you need to know what symbols are. Before ECMAScript 2015, JavaScript did not have a way to create private object properties. Developers used tricks like prefixes or closures to manage uniqueness. The introduction of Symbols solved this problem. A Symbol is a unique identifier created using the Symbol() function. Here are some key Well-Known Symbols: - Symbol.hasInstance: customizes the instanceof operator behavior - Symbol.isConcatSpreadable: determines if an object should be flattened when using Array.prototype.concat - Symbol.iterator: defines the default iterator for an object - Symbol.match: specifies a function used for pattern matching with regex - Symbol.replace: customizes the behavior of String.prototype.replace - Symbol.search: customizes the behavior of String.prototype.search - Symbol.split: determines how String.prototype.split performs on an object You can use Symbol.hasInstance to define custom behaviors for the instanceof operator. For example: class MyArray { static [Symbol.hasInstance](instance) { return Array.isArray(instance) && instance.length > 0; } } You can also use Symbol.iterator to define object iteration. For example: class Fibonacci { constructor() { this.current = 0; this.next = 1; } [Symbol.iterator]() { return this; } next() { const current = this.current; [this.current, this.next] = [this.next, this.current + this.next]; return { value: current, done: false }; } } Well-Known Symbols can streamline code and improve architecture. However, they can also impact performance. Using Symbols can incur a cost, especially when abstracting data structures or heavy computational tasks. Many modern frameworks and libraries use Well-Known Symbols for internal management. For example, React and Vue use Symbols to handle component states uniquely. To debug issues with Well-Known Symbols, you can use console logging and debugging tools like Chrome DevTools. Source: https://lnkd.in/d_8if4qz
To view or add a comment, sign in
-
JavaScript’s eval() — the feature everyone avoids, but few truly understand.. There’s a reason eval() has a bad reputation in JavaScript. But instead of just accepting “never use it”, I wanted to understand why. So I explored it—not for production use, but to understand how JavaScript actually thinks at runtime. What eval() really does At its core, eval() takes a string and executes it as JavaScript code in the current execution context. const x = 10; console.log(eval("x + 5")); // 15 This isn’t magic—it’s JavaScript dynamically injecting code into the engine’s execution phase. The real eye-opener: scope awareness What surprised me most is that direct eval has access to local scope: function testEval() { const secret = "hidden"; eval("console.log(secret)"); } testEval(); // "hidden" This single behavior explains both its power and its danger. It operates inside the scope chain, not outside it. Direct vs Indirect eval — a deep JS concept This distinction reveals how execution context is resolved: const x = 10; // Direct eval eval("x + 5"); // 15 // Indirect eval (0, eval)("x + 5"); // ReferenceError Indirect eval runs in the global scope, not the local one. This subtle difference says a lot about how JavaScript binds scope at runtime. Why JavaScript engines hate it. After experimenting, the concerns make total sense: Executes arbitrary code (huge security risk) Breaks JIT optimizations Defeats static analysis and makes debugging painful eval(userInput); // never trust runtime strings This is why linters, compilers, and senior engineers all warn against it. Does it have any valid use? In rare, tightly controlled scenarios—yes. For example, evaluating validated math expressions: function safeMath(expr) { if (!/^[0-9+\-*/() ]+$/.test(expr)) { throw new Error("Unsafe input"); } return eval(expr); } Even then, safer alternatives usually exist. My key takeaway Exploring eval() taught me far more than avoiding it ever could: How JavaScript resolves scope How execution contexts work Why some features exist even if we rarely use them How runtime behavior impacts performance and security Understanding what not to use is part of becoming a stronger engineer. I won’t use eval() in production—but I’m glad I understood it. Curiosity like this is what helps me write safer, more predictable JavaScript. #JavaScript #FrontendEngineering #WebDevelopment #JSInternals #LearningByDoing #SoftwareEngineering
To view or add a comment, sign in
-
🚀 JavaScript Event Loop — Explained Through Real Projects Most developers say: “Event loop handles async operations.” But in real frontend projects, understanding the event loop directly impacts: ✅ API handling ✅ UI smoothness ✅ Performance optimization ✅ Debugging tricky state issues. Let me explain how it shows up in real-world applications 👇 1️⃣ API Calls Don’t Block Your UI When we use: • fetch • axios • async/await • Promises async function getEvents() { const res = await axios.get("/api/events"); setEvents(res.data); } What actually happens: • API call goes to Web APIs • JS continues executing • Response callback goes to Microtask Queue • Event Loop pushes it to Call Stack • React re-renders 🔥 That’s why your UI doesn’t freeze while fetching data. 2️⃣ React State Updates Are Async. Have you ever faced this? setData(newData); console.log(data); // old value Why? Because state updates are scheduled — not immediate. Understanding the event loop helps avoid: •Incorrect assumptions •Double renders •Race conditions •Stale state bugs 3️⃣ Interview Favorite Question. setTimeout(() => console.log("Timeout"), 0); Promise.resolve().then(() => console.log("Promise")); Output: Promise Timeout Reason: • Promises → Microtask Queue (higher priority) • setTimeout → Macrotask Queue • Event Loop clears microtasks first. This question alone tests if you really understand JavaScript. 4️⃣ Real Bug I Faced in Production In a dashboard project: • API updated state • Immediately after, filtering logic ran • It used old state value • Result → Incorrect UI data. Fix: •Functional state updates. •Move dependent logic into useEffect. Understanding the event loop saved hours of debugging. 5️⃣ Performance & UI Freezing Heavy synchronous code blocks the call stack: for(let i = 0; i < 1000000000; i++) {} UI freezes ❌ Real-world solutions: •Break tasks using setTimeout. •Use requestAnimationFrame. •Use Web Workers for heavy processing. 🎯 Final Thought : If you: •Work with APIs •Use async/await daily •Build dashboards •Optimize performance. You are already relying on the Event Loop every single day. 👉 “I use JavaScript” from 🔥 “I understand how JavaScript works under the hood”. #JavaScript #FrontendDeveloper #ReactJS #WebDevelopment #EventLoop #AsyncProgramming #SoftwareEngineering #TechInterview
To view or add a comment, sign in
-
⚙️ JavaScript – Execution Context & Event Loop Understanding How JavaScript Works Internally JavaScript looks simple on the surface, but internally it follows a well-defined execution process. Understanding this helps you write better code and answer interview questions confidently. 🔹 What Is Execution Context? An execution context is the environment where JavaScript code is executed. There are three types: Global Execution Context Function Execution Context Eval Execution Context (rarely used) 🔹 Global Execution Context This is created when the JavaScript file runs. It contains: Global variables Global functions this keyword (refers to window in browsers) 👉 Created only once. 🔹 Function Execution Context Created whenever a function is called. It contains: Function arguments Local variables Inner functions Each function call creates a new execution context. 🔹 Execution Context Phases Every execution context has two phases: 1️⃣ Memory Creation Phase Variables are allocated memory Functions are stored completely Variables are initialized with undefined 2️⃣ Execution Phase Code is executed line by line Values are assigned Functions are invoked 👉 This explains hoisting. 🔹 Call Stack The call stack keeps track of execution contexts. Stack follows LIFO (Last In, First Out) Global context is at the bottom Function contexts are added and removed as needed Example: function one() { two(); } function two() { console.log("Hello"); } one(); 👉 two() is pushed, executed, then popped 👉 Then one() finishes 🔹 What Is the Event Loop? JavaScript is single-threaded, but it handles async operations using the event loop. The event loop continuously checks: Call Stack Callback Queue Microtask Queue 🔹 Web APIs Browser provides Web APIs for async tasks: setTimeout fetch DOM events These tasks run outside the call stack. 🔹 Callback Queue Holds callbacks from: setTimeout Event listeners Executed only when call stack is empty. 🔹 Microtask Queue Holds: Promise callbacks (then, catch) async / await 👉 Microtasks have higher priority than callback queue. 🔹 Event Loop Flow (Simple) Execute synchronous code Async tasks go to Web APIs Microtasks are executed first Callback queue executes next 👉 This explains async behavior clearly. 🧠 Simple Way to Remember Execution Context → where code runs Call Stack → manages execution Web APIs → handle async work Microtask Queue → promises first Callback Queue → timers & events Event Loop → manages everything ✅ Why Execution Context & Event Loop Matter Explains async JavaScript behavior Helps debug complex issues Very important for interviews Makes React & backend concepts easier Without this knowledge, async feels confusing. With this knowledge, everything clicks 🔥 #JavaScript #EventLoop #ExecutionContext #WebDevelopment #FrontendDevelopment #LearningInPublic #FullStackJourney
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
Please 🙏 there's no JS Event Loop! It is never mentioned in ECMA, because it has nothing to do with JS. More of that - a real loop with deterministic phases exists only in Node, implemented in libuv. Browsers use heuristics and priorities deciding what happens next, because they can't postpone render forever, yet must comply with ECMA. I am ok with people posting generated content, but why don't you care about its quality?