Stop guessing the order of your console.logs. 🛑 JavaScript is single-threaded. It has one brain and two hands. So, how does it handle a heavy API call, a 5-second timer, and a button click all at once without catching fire? It’s all about the Event Loop, but specifically, the "VIP treatment" happening behind the scenes. The Two Queues You Need to Know: 1. The Microtask Queue (The VIP Line) 💎 What lives here: Promises (.then), await, and MutationObserver. The Rule: The Event Loop is obsessed with this line. It will not move on to anything else until this queue is bone-dry. If a Promise creates another Promise, JS stays here until they are all done. 2. The Macrotask Queue (The Regular Line) 🎟️ What lives here: setTimeout, setInterval, and I/O tasks. The Rule: These tasks are patient. The Event Loop only picks one at a time, then goes back to check if any new VIPs (Microtasks) have arrived. The "Aha!" Moment Interview Question: What is the output of this code? (Most junior devs get this wrong). JavaScript console.log('Start'); setTimeout(() => console.log('Timeout'), 0); Promise.resolve().then(() => console.log('Promise')); console.log('End'); The Reality: 1. Start (Sync) 2. End (Sync) 3. Promise (Microtask - Jumps the line!) 4. Timeout (Macrotask - Even at 0ms, it waits for the VIPs) The Pro-Tip for Performance 💡 If you have a heavy calculation, don't wrap it in a Promise thinking it makes it "background." It’s still on the main thread! Use Web Workers if you really want to offload the heavy lifting. Does the Event Loop still confuse you, or did this click? Let's discuss in the comments! 👇 #JavaScript #WebDevelopment #CodingTips #SoftwareEngineering #Frontend
Understanding JavaScript's Event Loop and Microtask Queue
More Relevant Posts
-
JavaScript Closures are confusing… until they’re not ⚡ Most developers memorize the definition but struggle to actually understand it. Let’s simplify it 👇 💡 What is a closure? A closure is when a function 👉 remembers variables from its outer scope even after that scope is finished 🧠 Example: function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const fn = outer(); fn(); // 1 fn(); // 2 fn(); // 3 ⚡ Why this works: inner() still has access to count even after outer() has executed 🔥 Where closures are used: • Data hiding • State management • Event handlers • Custom hooks in React #JavaScript #FrontendDeveloper #ReactJS #CodingTips #WebDevelopment
To view or add a comment, sign in
-
After getting comfortable with JavaScript fundamentals, I moved to working with the browser. Part that makes websites actually feel alive , the DOM and browser APIs. This is where things became more practical. I explored: ▸ DOM Manipulation — traversing the page as a tree and dynamically updating elements, attributes, and styles with JS ▸ Events & Event Handling — capturing clicks, keyboard inputs, and user interactions to build truly responsive UIs ▸ Forms & Validation — handling input fields, text areas, and select boxes, with validation logic to keep data clean ▸ Timers & Intervals — managing delayed executions and repetitive actions using setTimeout and setInterval ▸ Data Storage — persisting user data across sessions with localStorage, sessionStorage, and cookies Along the way, I built a few mini projects to apply these concepts. There's a massive difference between understanding a concept and building with it. The projects made everything click. This phase felt different from just learning syntax. It was more about connecting logic to actual user interaction. #JavaScript #WebDevelopment #DOM #LearningInPublic #Frontend
To view or add a comment, sign in
-
🔁 Why does this print 4, 4, 4 — and not 1, 2, 3? One of the most common JavaScript interview questions, and it all comes down to one thing: the event loop. Look at this: for (var i = 1; i <= 3; i++) { setTimeout(() => console.log(i), 0) } What I expected when I started with Javascript: 1 2 3 What we actually get: 4 4 4 Why? 😓 😓 😓 JavaScript is single-threaded. When the loop runs, it doesn't pause and wait for setTimeout to fire. Instead, each callback gets placed in the task queue and runs only after the call stack is completely empty. So by the time any callback runs, the loop is already done — and i has already been incremented to 4. The callbacks don't hold a copy of i. They all share a reference to the same var i. And that i is now 4. But swap var for let — and suddenly it prints :1, 2, 3. Why? 😓 for (let i = 1; i <= 3; i++) { setTimeout(() => console.log(i), 0) } let is block-scoped. Each iteration of the loop gets its own brand new i( Imagine this , let is a self-centered guy who likes to live in his own bubble) So each callback closes over a separate variable — one holding 1, one holding 2, one holding 3. When the callbacks eventually run from the task queue, they each find their own i — untouched. var shares one variable across the whole loop. let creates a fresh one per iteration. That's the entire difference. #javascript #eventloop
To view or add a comment, sign in
-
Day 6 — Find Second Largest Number in an Array (JavaScript) Problem Write a function to find the second largest number in an array. Example Input: [10, 5, 8, 20] Output: 10 Approach First find the largest number, then find the largest number smaller than it. Code function secondLargest(arr){ let largest = -Infinity let second = -Infinity for(let i = 0; i < arr.length; i++){ if(arr[i] > largest){ second = largest largest = arr[i] } else if(arr[i] > second && arr[i] !== largest){ second = arr[i] } } return second } console.log(secondLargest([10,5,8,20])) Alternative Approach function secondLargest(arr){ let sorted = [...new Set(arr)].sort((a,b) => b-a) return sorted[1] } What I Learned How to track two maximum values in a single loop. #javascript #frontenddeveloper #codingpractice #webdevelopment
To view or add a comment, sign in
-
-
📌 Pressing Enter can submit a form, even without a click ❗ It’s not the button doing it ✔ It’s default browser behavior ✔ Inside a `<form>`: → Enter triggers the form’s default submit action ✔ Submission is owned by the form → not the button ✔ What actually happens: → browser listens for Enter in input fields → if a submit control exists (`type="submit"`) → it uses it → otherwise → it may still submit (built-in HTML behavior) 💡 That’s why: → login forms submit on Enter → even without clicking anything ❗ But here’s the catch: → no `<form>` → no submission → JS can stop it (`event.preventDefault()`) → frameworks often override this 💡 Core insight: → buttons don’t submit forms → forms submit forms → buttons just trigger it ✔ Many frontend bugs around forms → Enter not working → double submission → form not submitting ❗ They come from forgetting this one rule #CoreBits #WebDev #Frontend #JavaScript
To view or add a comment, sign in
-
🔍 JavaScript Quirk: == vs === (this will surprise you) Most devs say: 👉 “Always use ===” But do you know WHY? 👇 console.log(0 == false); console.log("" == false); console.log(null == undefined); 💥 Output: true true true Wait… WHAT? 😳 Why this happens? Because == does type coercion 👉 It converts values before comparing Step by step: ✔ false → 0 ✔ "" → 0 So internally: 0 == 0 // true 👉 Special case: null == undefined → true (but NOT equal to anything else) Now compare with === 👇 console.log(0 === false); console.log("" === false); 💥 Output: false false Because === checks: ✔ Value ✔ Type No conversion. No surprises. Now the WEIRDEST one 🤯 console.log([] == false); 💥 Output: true Why? [] → "" → 0 false → 0 👉 0 == 0 Yes… JavaScript really did that 😅 💡 Takeaway: ✔ == tries to be “smart” (and fails) ✔ === is strict and predictable ✔ Use === by default 👉 "Always use ===" is not a rule… It’s survival advice. 🔁 Save this (you’ll forget this later) 💬 Comment "===" if this clicked ❤️ Like for more JS quirks #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
Forced Synchronous Layout is one of those bugs that shows up as a long task in DevTools but is hard to pinpoint in the code. The pattern is deceptively simple: a class mutation followed immediately by a geometric property read (`scrollTop`, `getBoundingClientRect`…). The browser can't defer the layout — it recalculates right now, blocking the main thread. I've added a new snippet to WebPerf Snippets that detects it at runtime. Run it in DevTools, reproduce the interaction, and every FSL event gets logged with: - The property accessed and whether it was a read or write - The element descriptor (tagName + id/class) - Milliseconds since the last mutation - Full stack trace to locate the offending code One thing I had to work out while building it: MutationObserver fires asynchronously, so it can't catch mutations and geometric reads in the same synchronous block. The fix was intercepting `classList`, `setAttribute`, `setProperty`, and `cssText` directly at the prototype level, synchronously. Call `getFSLSummary()` for an aggregated report by property and element. Call `stopFSLDetector()` to restore all prototypes when you're done. https://lnkd.in/dhNciS5B #WebPerf #Performance #JavaScript #FrontEnd #WebPerfSnippets
To view or add a comment, sign in
-
🔍 JavaScript Bug You Might Have Seen (setTimeout vs Promise) You write this code: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); What do you expect? Start Timeout Promise End But actual output is: Start End Promise Timeout This happens because of the Event Loop 📌 What is the Event Loop? 👉 The event loop is the mechanism that decides which task runs next in JavaScript’s asynchronous execution. 📌 Priority order (very important): 1️⃣ Call Stack (synchronous code) 2️⃣ Microtask Queue 3️⃣ Macrotask Queue 📌 What’s inside each queue? 👉 Microtask Queue (HIGH priority): ✔ Promise.then / catch / finally ✔ queueMicrotask ✔ MutationObserver 👉 Macrotask Queue (LOWER priority): ✔ setTimeout ✔ setInterval ✔ setImmediate ✔ I/O tasks ✔ UI rendering events Execution flow: ✔ Step 1: Run all synchronous code 👉 Start → End ✔ Step 2: Execute ALL microtasks 👉 Promise ✔ Step 3: Execute macrotasks 👉 setTimeout So final order becomes: Start End Promise Timeout 💡 Takeaway: ✔ Microtasks run before macrotasks ✔ Promises > setTimeout ✔ setTimeout(fn, 0) is NOT immediate 👉 Understand queues = master async JS 🔁 Save this for later 💬 Comment “event loop” if this made sense ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
⚡ JavaScript Performance: Common Pitfalls Avoid these performance killers: 1. **DOM manipulation in loops** ```js // Bad for (let i = 0; i < 1000; i++) { document.body.appendChild(createElement()); } // Good const fragment = document.createDocumentFragment(); for (let i = 0; i < 1000; i++) { fragment.appendChild(createElement()); } document.body.appendChild(fragment); ``` 2. **Unnecessary re-renders in React** ```js // Use useMemo, useCallback, React.memo ``` 3. **Blocking the main thread** ```js // Use Web Workers for heavy computation ``` What's your biggest JavaScript performance fix? #JavaScript #Performance #Frontend #Optimization
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