🚀 My “Aha!” JavaScript Moment: Why does var print 3 three times? A few days ago, I was revisiting some JavaScript fundamentals… and I came across this classic piece of code 👇 for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } I expected: 0 1 2 But guess what I got? 3 3 3 😅 I paused for a second and thought — “Wait… what just happened?” 🧠 The Moment of Clarity Here’s what’s really going on: var in JavaScript is function-scoped, not block-scoped. So inside that for loop, all iterations share one single i variable. By the time the setTimeout callbacks actually run (after 1 second), the loop has already finished — and i has become 3. So all three callbacks look at the same i, and print 3. Boom 💥 — mystery solved. ✅ The Fix? Use let When we switch to let, something magical happens: for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } Now, let is block-scoped, meaning each iteration gets its own copy of i. Each callback “remembers” the value from that iteration. Result: 0 1 2 💡 My Mental Model I now think of it like this: Using var: one whiteboard where you keep erasing and writing new numbers. Everyone who looks later sees the same final number. Using let: each student gets their own notepad — they all remember their own number. 🧩 Key Takeaway Keyword Scope Loop Behavior Output var Function-scoped Shared variable 3, 3, 3 let Block-scoped New variable each iteration 0, 1, 2 We often jump into frameworks, async/await, and APIs… but sometimes it’s these small, fundamental details that sharpen our understanding the most. 🔍 Have you ever had an “aha!” moment like this in JavaScript (or another language)? Share it below — I’d love to hear your story 👇 #JavaScript #WebDevelopment #AsyncJS #Frontend #FullStackDeveloper #LearningToCode #CodingJourney #Developers #CareerGrowth
Vineet Prajapati’s Post
More Relevant Posts
-
🌱 Back to Learning JavaScript (Deep Dive Edition) JavaScript’s async behavior isn’t just about the Event Loop it’s powered by two hidden players: Microtasks and Macrotasks. Here’s what I learned after diving deeper. 👉 Microtasks vs Macrotasks We all know the Event Loop keeps JavaScript non-blocking… But what many developers don’t realize is that there are actually two separate queues managing async tasks. 🔹 Microtask Queue Handles: Promise.then(), async/await, queueMicrotask(), MutationObserver Executes immediately after the current synchronous code — before rendering or macrotasks. 🔹 Macrotask Queue (Task Queue) Handles: setTimeout, setInterval, setImmediate, I/O, and fetch callbacks Runs after all microtasks are cleared. Example: console.log("Start"); setTimeout(() => console.log("Macrotask (Timeout)"), 0); Promise.resolve().then(() => console.log("Microtask (Promise)")); console.log("End"); Output: Start End Microtask (Promise) Macrotask (Timeout) 🔎 Something most people don’t know: If microtasks keep queuing themselves (like nested Promises), the browser can’t render causing what’s known as microtask starvation. ✨ Bonus Tip: Rendering happens between macrotasks, not microtasks. That’s why blocking the microtask queue can make your UI feel frozen. 🔑 Takeaway: Knowing how JavaScript schedules microtasks vs macrotasks gives you real control over async behavior, performance, and rendering smoothness. #JavaScript #AsyncProgramming #WebDevelopment #Frontend #EventLoop #JavaScriptInternals #Promises #CodingJourney #LearnInPublic #100DaysOfCode
To view or add a comment, sign in
-
💡 JavaScript Event Loop Explained Visually! Ever wondered why Promise runs before setTimeout() even when the timeout is 0ms? 🤔 Let’s break it down step-by-step 👇 1️⃣ console.log('Start!') → Runs immediately. 2️⃣ setTimeout(...) → Sent to the Web API, then moves to the Macrotask Queue. 3️⃣ Promise.resolve(...) → Sent to the Microtask Queue. 4️⃣ console.log('End!') → Runs next. 5️⃣ Event loop checks → Executes Microtasks first (Promise!). 6️⃣ Then Macrotasks (Timeout!). ✅ Final Output: Start! End! Promise! Timeout! Even though JavaScript is single-threaded, it feels asynchronous thanks to the Event Loop, Microtasks, and Macrotasks working together in perfect sync. By understanding this flow, you can write more efficient and predictable asynchronous code a must for every modern JavaScript developer. ⚡ 🚀 Key takeaway: The Event Loop is the heart of JavaScript’s async behavior once you master it, async code starts making complete sense. 💬 What was your first “Aha!” moment when learning about the Event Loop? Let’s discuss below 👇 #JavaScript #WebDevelopment #EventLoop #AsyncProgramming #CodingTips #Frontend #NodeJS #ProgrammingConcepts #TechEducation #Developers #JSFacts #CodeLearning
To view or add a comment, sign in
-
-
☕ Revisiting JavaScript Event Flow — Capturing, Target & Bubbling Phases Today, I was revising one of the most important concepts in JavaScript — Events and Event Listeners. 💡 It’s fascinating how a single click can travel through multiple layers of the DOM before reaching its destination! Here’s what I learned and revised 👇 🔹 Event & Event Listener JavaScript allows us to respond to user interactions like clicks, key presses, and mouse movements. For example 👇 element.addEventListener("click", () => { console.log("Element clicked!"); }); This method lets us attach multiple handlers to the same element without overwriting existing ones. 🔹 Click Event The click event is one of the most commonly used — and it’s the one I focused on today while understanding how event flow actually works. 🔹 Event Flow in JavaScript Every event in the DOM passes through three phases: 1️⃣ Capturing Phase – The event travels from the top (document) down to the target element. 2️⃣ Target Phase – The exact element that triggered the event receives it. 3️⃣ Bubbling Phase – The event then bubbles back up toward the document. 📘 Example // Capturing phase parent.addEventListener("click", () => { console.log("Parent clicked - Capturing Phase"); }, true); // true → capturing // Bubbling phase (default) child.addEventListener("click", () => { console.log("Child clicked - Bubbling Phase"); }); 👉 When you pass true as the third argument in addEventListener, it listens during the capturing phase. 👉 By default, it’s false, meaning the listener works in the bubbling phase. 🧠 Visual Flow 📤 Document → HTML → Body → Parent → Child → (then bubbles back up 🔁) Understanding this complete flow helped me clearly visualize how events travel and how to control them precisely using capturing and bubbling. 🚀 A huge thanks to CoderArmy, Rohit Negi, and Aditya Tandon Sir 🙏 Your clear explanations and practical examples made this topic so easy to grasp. #JavaScript #EventListener #EventFlow #FrontendDevelopment #WebDevelopment #LearningJourney #Coding #Developer #RohitNegi #AdityaTandon #CoderArmy
To view or add a comment, sign in
-
🚀 #Day 3 Understanding JavaScript Event Loop & React useEffect Timing Today, I took a deep dive into one of the most powerful — yet often confusing — topics in JavaScript: the Event Loop 🔁 At first, it looked complex. But once I started writing small examples and observing outputs step-by-step, everything became crystal clear 💡 🔍 What I learned: 🧠 The Event Loop JavaScript is a single-threaded language — meaning it can execute only one task at a time. But thanks to the Event Loop, it can still handle asynchronous operations (like setTimeout, fetch, or Promise) efficiently without blocking the main thread. Here’s how it works 👇 1️⃣ Call Stack — Executes synchronous code line by line. 2️⃣ Web APIs — Handles async tasks (like timers, fetch). 3️⃣ Microtask Queue — Holds resolved Promises and async callbacks. 4️⃣ Callback Queue — Stores setTimeout, setInterval callbacks. The Event Loop continuously checks: “Is the call stack empty? If yes, then push the next task from the microtask queue — and then from the callback queue.” That’s how JavaScript manages async code without breaking the flow ⚡ ⚛️ In React: useEffect() runs after the component renders, and async tasks inside it still follow the Event Loop rules. That’s why: console.log("Start"); setTimeout(() => console.log("Timeout"), 0); Promise.resolve().then(() => console.log("Promise")); console.log("End"); Output: Start → End → Promise → Timeout ✅ 💬 Takeaway: Once you understand the Event Loop, async code and React effects start making perfect sense! #JavaScript #ReactJS #FrontendDevelopment #EventLoop #AsyncProgramming #WebDevelopment #ReactHooks #LearningInPublic #DevelopersJourney #CodeBetter
To view or add a comment, sign in
-
-
JavaScript Concept — “The Power of Closures” 💭 Ever wondered how JavaScript functions “remember” the variables around them? That’s the magic of Closures — one of JavaScript’s most elegant features. Closures allow a function to access variables from its outer scope, even after that scope has closed. This concept powers some of the most powerful patterns in JS — from private variables to event handlers. Here’s a small example 👇 function counter() { let count = 0; return function() { count++; return count; }; } const add = counter(); console.log(add()); // 1 console.log(add()); // 2 It’s simple, elegant, and shows how deep JavaScript really is. #JavaScript #WebDevelopment #Coding #Frontend #Learning
To view or add a comment, sign in
-
Those little question marks in JavaScript? They finally make sense now. 😅 💡 Today I learned something subtle but super useful in JavaScript! Those little question marks ? and ?? actually do a lot more than I thought Here’s what clicked for me today ✅ ?? – Nullish Coalescing Operator Returns the right-hand value only if the left-hand side is null or undefined. So it helps you set true defaults without breaking valid falsy values like 0 or "". let count = 0; console.log(count || 10); // 10 (because 0 is falsy) console.log(count ?? 10); // 0 (because 0 is not null/undefined) ✅ || – Logical OR Operator Returns the right-hand side if the left-hand side is falsy (false, 0, "", null, undefined, NaN). It’s great for simple fallbacks - but not when 0 or an empty string are valid values. ✅ ?. – Optional Chaining Safely accesses nested properties without throwing an error. console.log(user?.profile?.email); ✅ ? : – Ternary Operator A clean one-liner for conditions: let age = 20; let status = age >= 18 ? "Adult" : "Minor"; I love how small syntax choices like "?? " vs || can make code both safer and more expressive. Feels like I leveled up my JavaScript brain today 😄 #JavaScript #TodayILearned #WebDevelopment #CodeTips #Frontend
To view or add a comment, sign in
-
Understanding this in JavaScript this — one of the most misunderstood keywords in JavaScript. It’s simple in theory… until it suddenly isn’t 😅 Here’s what makes it tricky — this depends entirely on how a function is called, not where it’s written. Its value changes with context. Let’s look at a few examples 👇 const user = { name: "Sakura", greet() { console.log(`Hello, I am ${this.name}`); }, }; user.greet(); // "Sakura" ✅ const callGreet = user.greet; callGreet(); // undefined ❌ (context lost) const boundGreet = user.greet.bind(user); boundGreet(); // "Sakura" ✅ (context fixed) Key takeaways 🧠 ✅ this refers to the object that calls the function. ✅ Lose the calling object → lose the context. ✅ Use .bind(), .call(), or .apply() to control it. ✅ Arrow functions don’t have their own this — they inherit from the parent scope. These small details often trip up developers in interviews and real-world debugging sessions. Once you understand the context flow, this becomes a lot less scary to work with. 💪 🎥 I simplified this in my Day 28/50 JS short video— check it out here 👇 👉 https://lnkd.in/gyUnzuZA #javascript #webdevelopment #frontend #backend #programming #learnjavascript #softwaredevelopment #developerslife #techsharingan #50daysofjavascript
To view or add a comment, sign in
-
Today I Learned: Iterators & Generators in JavaScript One of the most interesting parts of modern JavaScript is how it handles iteration, and today I finally understood how Iterators and Generators work under the hood! 🧠 1. Iterators An iterator is simply an object that defines how to step through a sequence, one value at a time. It follows the pattern: const iterator = [10, 20, 30][Symbol.iterator](); console.log(iterator.next()); // { value: 10, done: false } console.log(iterator.next()); // { value: 20, done: false } Each call to .next() gives you the next value until done: true. ⚙️ Generators A generator function (defined with function*) automatically creates an iterator for you. function* greet() { yield "Hi"; yield "Hello"; yield "Hey"; } const it = greet(); console.log(it.next().value); // Hi console.log(it.next().value); // Hello What’s cool is that you can pause and resume function execution! 🔥 💡 Key Takeaway: Iterators let you take control of how data is accessed. Generators make it easier to build your own iterators — letting you write asynchronous, lazy, and powerful code structures. Every day, I’m realising how deep JavaScript really is — and how beautiful its design becomes when you understand what’s happening under the hood. #JavaScript #WebDevelopment #LearningInPublic #BackendDevelopment #ES6
To view or add a comment, sign in
-
🚀 Understanding the JavaScript Event Loop Have you ever wondered how JavaScript — a single-threaded language — handles async tasks like setTimeout(), fetch(), or Promises without freezing the browser? 🤔 That’s where the Event Loop comes in! 🌀 ⚙️ How it works 1️⃣ Call Stack → Executes synchronous code (like console.log()). 2️⃣ Web APIs → Handle async tasks (like timers or network requests). 3️⃣ Callback Queues Microtask Queue → Handles Promises and async/await. Macrotask Queue → Handles setTimeout, setInterval, etc. 4️⃣ Event Loop → Continuously checks: > “Is the call stack empty?” If yes → It pushes queued callbacks back to the stack for execution. 🧠 Example: console.log("A"); setTimeout(() => console.log("B"), 0); Promise.resolve().then(() => console.log("C")); console.log("D"); Output: A D C B Because ➡️ A & D → run first (synchronous). C → from Promise (microtask). B → from setTimeout (macrotask). 💡 Takeaway > Event Loop makes JavaScript feel asynchronous — even though it runs on a single thread! ⚡ 🔖 #JavaScript #EventLoop #WebDevelopment #AsyncJS #Frontend #Angular #React #CodingTips
To view or add a comment, sign in
-
🚀 Day 2 — Mastering Closures in JavaScript Today I explored one of the most powerful concepts in JavaScript — Closures. It’s amazing how a function can “remember” the variables from its outer scope even after that outer function has finished executing! 🧠 Here’s what I learned and understood today: 🔍 What is a Closure: A closure is formed when an inner function remembers and accesses variables from its outer function — even after the outer function has returned. 🧩 Lexical Scope: JavaScript uses lexical scoping — meaning, a function’s scope is determined by where it is defined, not where it’s called. ⚙️ Closure Use Cases: Used for data privacy, maintaining state, creating function factories, and managing async operations elegantly. 🔁 Closures in Loops: I learned how closures help capture the correct variable values inside loops — especially when using var, let, and asynchronous code. 🔒 Private Variables with Closures: Closures can hide data from the global scope, allowing us to create private variables and methods, just like in OOP. 📦 Module Pattern with Closures: The module pattern uses closures to bundle related functionality together, providing encapsulation and privacy — the backbone of reusable JS design. 🧮 Memory Implications: Since closures keep references to outer variables, understanding memory management is crucial to prevent leaks in long-running applications. I learn how JavaScript manages scope, memory, and data privacy behind the scenes. #JavaScript #Closures #WebDevelopment #Frontend #Day2 #Coding #LearningJourney
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