🚀 𝐃𝐚𝐲 6 – 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐄𝐯𝐞𝐧𝐭 𝐋𝐨𝐨𝐩 (𝐒𝐢𝐦𝐩𝐥𝐞 & 𝐂𝐥𝐞𝐚𝐫) JavaScript is single-threaded… 👉 But then how does it handle things like `setTimeout`? 🤔 Let’s understand the real flow 👇 --- 💡 The Setup JavaScript uses: * Call Stack → runs code * Web APIs → handles async tasks * Callback Queue → waits for execution * Event Loop → manages everything --- 💡Example: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); console.log("End"); --- 💡 Output: Start End Timeout --- 💡 Why? (Step-by-step) * `Start` → runs immediately * `setTimeout` → sent to Web APIs * `End` → runs immediately * Timer completes → callback goes to Queue * Event Loop checks → Stack empty * Callback pushed to Stack → executes --- ⚡ Key Insight 👉 Even with `0ms`, it does NOT run immediately 👉 It waits until the Call Stack is empty --- 💡 Simple Mental Model 👉 “Async code runs after sync code finishes” --- 💡 Why this matters? Because it explains: * execution order * async behavior * common bugs --- 👨💻 Continuing my JavaScript fundamentals series 👉 Next: **Promises (Async Made Better)** 👀 #JavaScript #WebDevelopment #FrontendDevelopment #Coding #SoftwareEngineer #Tech
JavaScript Event Loop Explained with setTimeout Example
More Relevant Posts
-
🚨 JavaScript Gotcha: Objects as Keys?! Take a look at this 👇 const a = {}; const b = { key: 'b' }; const c = { key: 'c' }; a[b] = 123; a[c] = 456; console.log(a[b]); // ❓ 👉 What would you expect? 123 or 456? 💡 Actual Output: 456 🤯 Why does this happen? In JavaScript, object keys are always strings or symbols. So when you use an object as a key: a[b] → a["[object Object]"] a[c] → a["[object Object]"] Both b and c are converted into the same string: "[object Object]" ⚠️ That means: a[b] = 123 sets " [object Object] " → 123 a[c] = 456 overwrites it → 456 So finally: console.log(a[b]); // 456 🧠 Key Takeaways ✅ JavaScript implicitly stringifies object keys ✅ Different objects can collide into the same key ❌ Using objects as keys in plain objects is unsafe 🔥 Pro Tip If you want to use objects as keys, use a Map instead: const map = new Map(); map.set(b, 123); map.set(c, 456); console.log(map.get(b)); // 123 ✅ ✔️ Map preserves object identity ✔️ No unexpected overwrites 💬 Final Thought JavaScript often hides complexity behind simplicity. Understanding these small quirks is what separates a developer from an expert. #JavaScript #WebDevelopment #FrontendDevelopment #Programming #Coding #JavaScriptTips #JSConfusingParts #DevelopersLife #CodeNewbie #LearnToCode #SoftwareEngineering #TechTips #CodeQuality #CleanCode #100DaysOfCode #ProgrammingTips #DevCommunity #CodeChallenge #Debugging #JavaScriptDeveloper #MERNStack #FullStackDeveloper #ReactJS #NodeJS #WebDevTips #CodingLife
To view or add a comment, sign in
-
-
🚀 **𝐃𝐚𝐲 5 – 𝐇𝐨𝐢𝐬𝐭𝐢𝐧𝐠 𝐢𝐧 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 (𝐂𝐥𝐞𝐚𝐫 & 𝐏𝐫𝐚𝐜𝐭𝐢𝐜𝐚𝐥 𝐄𝐱𝐩𝐥𝐚𝐧𝐚𝐭𝐢𝐨𝐧)** You might have seen this 👇 👉 Using a variable before declaring it But why does this work? 🤔 --- 💡 **What is Hoisting?** Hoisting means: 👉 Before execution, JavaScript **allocates memory for variables and functions** 👉 In simple words: **Declarations are processed before code runs** --- 💡 **Example:** ```js id="d5pro1" console.log(a); var a = 10; ``` 👉 Output: `undefined` --- 💡 **What actually happens behind the scenes?** Before execution (Memory Phase): * `a` → undefined Then execution starts: * `console.log(a)` → prints undefined * `a = 10` --- 💡 **Important Rule** 👉 JavaScript only hoists **declarations**, not values --- 💡 **var vs let vs const** 👉 **var** * Hoisted * initialized as `undefined` * can be accessed before declaration 👉 **let & const** * Hoisted * BUT not initialized --- ⚠️ **Temporal Dead Zone (TDZ)** This is the time between: 👉 variable declared 👉 and initialized During this: ❌ Accessing variable → **ReferenceError** --- 💡 **Example:** ```js id="d5pro2" console.log(a); let a = 10; ``` 👉 Output: **ReferenceError** --- ⚡ **Key Insight (Very Important)** 👉 Hoisting is NOT moving code 👉 It’s just **memory allocation before execution** --- 💡 **Why this matters?** Because it helps you understand: * unexpected `undefined` values * ReferenceErrors * how JavaScript actually runs code --- 👨💻 Continuing my JavaScript fundamentals series 👉 Next: **JavaScript Runtime & Event Loop** 👀 #JavaScript #WebDevelopment #FrontendDevelopment #Coding #SoftwareEngineer #Tech
To view or add a comment, sign in
-
-
JavaScript is easy. Until it isn't. 😅 Every developer has been there. You're confident. Your code looks clean. You hit run. And then: " Cannot read properties of undefined (reading 'map') " The classic JavaScript wall. Here are 7 JavaScript mistakes I see developers make constantly and how to fix them: 1. Not understanding async/await ⚡ → Wrong: | const data = fetch('https://lnkd.in/dMDBzbsK'); console.log(data); // Promise {pending} | → Right: | const data = await fetch('https://lnkd.in/dMDBzbsK'); | 2. Using var instead of let/const → var is function scoped and causes weird bugs → Always use const by default. let when you need to reassign. Never var. 3. == instead of === → 0 == "0" is true in JavaScript 😱 → Always use === for comparisons. Always. 4. Mutating state directly in React → Wrong: user.name = "Shoaib" → Right: setUser({...user, name: "Shoaib"}) 5. Forgetting to handle errors in async functions → Always wrap await calls in try/catch → Silent failures are the hardest bugs to track down 6. Not cleaning up useEffect in React → Memory leaks are real → Always return a cleanup function when subscribing to events 7. Treating arrays and objects as primitives → [] === [] is false in JavaScript → Reference types don't compare like numbers — learn this early JavaScript rewards the developers who understand its quirks. 💡 Which of these caught YOU off guard when you first learned it? 👇 #JavaScript #WebDevelopment #Frontend #FullStackDeveloper #React #Programming #CodingTips #Developer #Tech #Pakistan #LearnToCode #JS #SoftwareEngineering #100DaysOfCode #PakistaniDeveloper
To view or add a comment, sign in
-
-
JavaScript isn’t asynchronous… the environment is. After diving deep into asynchronous JavaScript, I realized something that completely changed how I think about writing code: We don’t “wait” for data… we design what happens when it arrives. 💡 Most developers use fetch and Promises daily, but very few truly understand what happens under the hood. Here’s the real mental model: 🔹 JavaScript is single-threaded 🔹 Heavy operations (API calls, timers) are offloaded to Web APIs 🔹 fetch() returns a Promise immediately (not the data!) 🔹 .then() doesn’t execute your function… it registers it for later 🔥 The game changer? There are actually two queues, not one: Microtask Queue (Promises) → HIGH PRIORITY Callback Queue (setTimeout, etc.) And the Event Loop always prioritizes microtasks. 💥 Example: console.log("1"); setTimeout(() => console.log("2"), 0); Promise.resolve().then(() => console.log("3")); console.log("4"); 👉 Output: 1 . 4 . 3 . 2 🧠 Why this matters: Explains unexpected execution order Makes debugging async code 10x easier Helps avoid common interview pitfalls Builds a strong foundation for React & modern frontend ⚡ Key Insight: Promises are not about cleaner syntax… They are about controlling time and execution order in a non-blocking environment. 📌 Once you truly understand: Event Loop Microtask vs Callback Queue Promise lifecycle You stop guessing… and start predicting behavior. #JavaScript #Frontend #WebDevelopment #AsyncJS #Promises #EventLoop #React #Programming
To view or add a comment, sign in
-
-
𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝘁𝗵𝗲 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽 JavaScript runs one thing at a time. One slow task freezes your screen. You wonder how apps stay fast. The Event Loop solves this. It manages three main parts. - Call Stack: Runs your code line by line. - Web APIs: Handles timers and API calls. - Queues: Holds callbacks until they run. Queues have levels. - Microtasks: Promises. These have high priority. - Macrotasks: Timers and DOM events. These have low priority. How it works. 1. Sync code runs on the stack. 2. Async tasks move to Web APIs. 3. Finished tasks move to queues. 4. The Event Loop waits for the stack to empty. 5. It pushes microtasks first. 6. It pushes macrotasks last. Look at this example. console.log(Start) setTimeout(Timeout, 0) Promise.then(Promise) console.log(End) The output is: Start End Promise Timeout Why? Start and End run first. The Promise is a microtask. It runs next. The timeout is a macrotask. It runs last. A common mistake is thinking setTimeout 0 runs immediately. It does not. It waits for the stack to empty. It waits for all microtasks to finish. This logic stops async bugs. Understand the loop to write better code. Source: https://lnkd.in/gjBYnFZB
To view or add a comment, sign in
-
⚡ Day 7 — JavaScript Event Loop (Explained Simply) Ever wondered how JavaScript handles async tasks while being single-threaded? 🤔 That’s where the Event Loop comes in. --- 🧠 What is the Event Loop? 👉 The Event Loop manages execution of code, async tasks, and callbacks. --- 🔄 How it works: 1. Call Stack → Executes synchronous code 2. Web APIs → Handle async tasks (setTimeout, fetch, etc.) 3. Callback Queue / Microtask Queue → Stores callbacks 4. Event Loop → Moves tasks to the stack when it’s empty --- 🔍 Example: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); --- 📌 Output: Start End Promise Timeout --- 🧠 Why? 👉 Microtasks (Promises) run before macrotasks (setTimeout) --- 🔥 One-line takeaway: 👉 “Event Loop decides what runs next in async JavaScript.” --- If you're learning async JS, understanding this will change how you debug forever. #JavaScript #EventLoop #WebDevelopment #Frontend #100DaysOfCode 🚀
To view or add a comment, sign in
-
🚀 Understanding Factory Functions in JavaScript Ever felt confused using constructors and the new keyword? 🤔 That’s where Factory Functions make life easier! 👉 A Factory Function is simply a function that creates and returns objects. 💡 Why use Factory Functions? ✔️ No need for new keyword ✔️ Easy to understand (perfect for beginners) ✔️ Avoids this confusion ✔️ Helps in writing clean and reusable code ✔️ Supports data hiding using closures 🧠 Example: function createUser(name, age) { return { name, age, greet() { console.log("Hello " + name); } }; } const user = createUser("Sushant", 21); user.greet(); ⚠️ One downside: Methods are not shared (can use more memory) 🎯 Conclusion: Factory Functions are a great way to start writing clean and maintainable JavaScript code without complexity. #JavaScript #WebDevelopment #FrontendDeveloper #CodingJourney #LearnToCode #100DaysOfCode
To view or add a comment, sign in
-
-
JavaScript is easy to learn, but mastering it is what separates the juniors from the seniors. 🚀 Whether you are building a simple landing page or a complex full-stack application, your JS fundamentals dictate your code quality. Here are 3 tips to level up your JavaScript game today: **1. Master Modern Syntax (ES6+)** Stop using `var`. Start leveraging optional chaining (`?.`), nullish coalescing (`??`), and destructuring. These aren’t just "syntax sugar"—they make your code more readable and significantly less prone to "undefined" errors. **2. Understand the Event Loop** JavaScript is single-threaded, but it’s a powerhouse. If you don't understand how the Call Stack, Web APIs, and the Task Queue interact, you’ll eventually run into "mysterious" performance bottlenecks. Learn how the engine handles concurrency to write non-blocking code. **3. Move Beyond console.log()** Debugging is 50% of the job. Start using `console.table()` for arrays of objects, `console.time()` to measure performance, and learn to use the "Debugger" statement to pause execution and inspect the scope. The ecosystem moves fast, but the fundamentals are forever. What’s one JS feature you can’t live without? Let’s discuss in the comments! 👇 #JavaScript #WebDevelopment #ProgrammingTips #Coding #SoftwareEngineering #TechCommunity
To view or add a comment, sign in
-
JavaScript is easy to learn, but mastering it is what separates the juniors from the seniors. 🚀 Whether you are building a simple landing page or a complex full-stack application, your JS fundamentals dictate your code quality. Here are 3 tips to level up your JavaScript game today: **1. Master Modern Syntax (ES6+)** Stop using `var`. Start leveraging optional chaining (`?.`), nullish coalescing (`??`), and destructuring. These aren’t just "syntax sugar"—they make your code more readable and significantly less prone to "undefined" errors. **2. Understand the Event Loop** JavaScript is single-threaded, but it’s a powerhouse. If you don't understand how the Call Stack, Web APIs, and the Task Queue interact, you’ll eventually run into "mysterious" performance bottlenecks. Learn how the engine handles concurrency to write non-blocking code. **3. Move Beyond console.log()** Debugging is 50% of the job. Start using `console.table()` for arrays of objects, `console.time()` to measure performance, and learn to use the "Debugger" statement to pause execution and inspect the scope. The ecosystem moves fast, but the fundamentals are forever. What’s one JS feature you can’t live without? Let’s discuss in the comments! 👇 #JavaScript #WebDevelopment #ProgrammingTips #Coding #SoftwareEngineering #TechCommunity
To view or add a comment, sign in
-
🚀 JavaScript Event Loop Explained (A Must-Know Concept) If you've ever wondered why setTimeout(fn, 0) doesn’t run immediately or how JS handles async tasks while being single-threaded — this is where the Event Loop comes in. Let’s break it down 👇 🧠 1. JavaScript is Single-Threaded JS runs one thing at a time using a Call Stack. Functions are pushed → executed → popped Only synchronous code runs here 🌐 2. Web APIs (Browser Magic) When JS encounters async operations: setTimeout, fetch, DOM events 👉 They are handled outside JS by Web APIs Once done, they don’t go to the stack directly… 📬 3. Queues (Where async waits) There are 2 types of queues: 🔹 Microtask Queue (High Priority) Promise.then() queueMicrotask() MutationObserver 🔸 Macrotask Queue (Low Priority) setTimeout() setInterval() DOM events 🔄 4. Event Loop (The Brain) The Event Loop keeps checking: 1️⃣ Is Call Stack empty? 2️⃣ Run ALL Microtasks 🟢 3️⃣ Then run ONE Macrotask 🟡 4️⃣ Repeat 🔁 💡 Example: console.log(1); setTimeout(() => console.log(2), 0); Promise.resolve().then(() => console.log(3)); console.log(4); 📌 Output: 👉 1 → 4 → 3 → 2 🔥 Why? 1, 4 → synchronous → run first 3 → microtask → higher priority 2 → macrotask → runs last ⚡ Pro Tips ✔ Microtasks always run before macrotasks ✔ Even setTimeout(fn, 0) is NOT immediate ✔ Too many microtasks can block UI (⚠️ starvation) 🎯 Why You Should Care Understanding the Event Loop helps you: Write better async code Debug tricky timing issues Ace JavaScript interviews 💼 💬 If this clarified things, drop a 👍 or comment your doubts — happy to help! #JavaScript #WebDevelopment #Frontend #NodeJS #Coding #Programming #SoftwareEngineering
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