🔍 JavaScript Bug You Might Have Seen (setTimeout + loop) You write this code: for (var i = 1; i <= 3; i++) { setTimeout(() => { console.log(i); }, 1000); } You expect: 1 2 3 But you get: 4 4 4 This happens because of closure 📌 What is a Closure? 👉 A closure is a function along with its lexical environment. Not clear? No problem. Here’s a simpler version: 👉 A closure is a function along with the variables it remembers from where it was created. In this case: The function inside setTimeout 👉 remembers the SAME i variable And when it executes: 👉 Loop has already finished → i = 4 So all logs print: 4, 4, 4 How to fix it? ✔ Use let (creates a new variable per iteration) for (let i = 1; i <= 3; i++) { setTimeout(() => { console.log(i); }, 1000); } ✔ Or create a new scope manually for (var i = 1; i <= 3; i++) { (function(i) { setTimeout(() => { console.log(i); }, 1000); })(i); } 💡 Takeaway: ✔ Closures remember variables, not values ✔ var shares the same scope → leads to bugs ✔ let creates a new scope per iteration 👉 If you understand closures, you’ll avoid some very tricky bugs. 🔁 Save this for later 💬 Comment “closure” if this made sense ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
JavaScript Bug: Closure Gotcha with setTimeout and Loop
More Relevant Posts
-
🔍 JavaScript Behavior You Might Have Seen (Function Declaration vs Expression) You write this: sayHi(); function sayHi() { console.log("Hello"); } 👉 Works perfectly ✅ Now try this: sayHello(); const sayHello = function () { console.log("Hello"); }; 👉 ReferenceError ❌ Same idea… same function… Why different behavior? This happens because of Hoisting 📌 What’s happening here? 👉 Function Declarations are fully hoisted So internally: function sayHi() { console.log("Hello"); } sayHi(); 👉 That’s why it works even before definition But for Function Expressions: const sayHello = function () {} 👉 This is treated like a variable (const) So internally: const sayHello; // not initialized (TDZ) sayHello(); // ❌ error 📌 Key Difference: ✔ Function Declaration 👉 Hoisted completely (can call before definition) ✔ Function Expression 👉 Not hoisted like function 👉 Behaves like variable 📌 Bonus case 👇 var sayHello = function () { console.log("Hello"); }; sayHello(); 👉 Works (because var is hoisted) BUT: sayHello(); // before assignment 👉 TypeError ❌ (not a function yet) 💡 Takeaway: ✔ Function declarations → fully hoisted ✔ Function expressions → behave like variables ✔ let/const → TDZ error ✔ var → undefined (then TypeError if called) 👉 Same function… different behavior based on how you write it 🔁 Save this before it confuses you again 💬 Comment “function” if this clicked ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
🔍 JavaScript Behavior You Might Have Seen (Hoisting) You write this: console.log(a); var a = 10; You expect: 👉 ReferenceError But you get: 👉 undefined 🤯 Now try this: console.log(b); let b = 20; 👉 This time you get: ReferenceError ❌ Same with: console.log(c); const c = 30; 👉 Error again ❌ Now look at functions 👇 sayHi(); function sayHi() { console.log("Hello"); } 👉 This works ✅ But this doesn’t: sayHello(); const sayHello = function () { console.log("Hello"); }; 👉 ReferenceError ❌ Why different behavior? This happens because of Hoisting 📌 What is Hoisting? 👉 Hoisting is JavaScript’s behavior of moving declarations to the top of their scope before execution. 📌 What’s actually happening? ✔ var: var a; console.log(a); // undefined a = 10; 👉 Hoisted + initialized ✔ let / const: 👉 Hoisted but NOT initialized 👉 Access before declaration → ReferenceError 👉 (Temporal Dead Zone) ✔ Function declarations: function sayHi() {} 👉 Fully hoisted (can be called before definition) ✔ Function expressions: const sayHello = function () {} 👉 Behave like variables 👉 Not usable before declaration 💡 Takeaway: ✔ var → hoisted + initialized ✔ let / const → hoisted but restricted (TDZ) ✔ Function declarations → fully hoisted ✔ Function expressions → NOT hoisted like functions 👉 Same concept… different rules 🔁 Save this before hoisting confuses you again 💬 Comment “hoisting” 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 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 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
-
🔍 JavaScript Quirk: Hoisting (var vs let vs const) JavaScript be like: 👉 “I know your variables… before you even write them” 😅 Let’s see the magic 👇 console.log(a); var a = 10; 💥 Output: undefined Wait… no error? 🤯 Why? Because `var` is **hoisted** 📌 What is Hoisting? Hoisting is JavaScript’s behavior of **moving variable and function declarations to the top of their scope before execution**. 👉 JS internally does this: var a; console.log(a); // undefined a = 10; So the variable exists… but has no value yet. Now try with `let` 👇 console.log(b); let b = 20; 💥 Output: ReferenceError ❌ Same with `const` 👇 console.log(c); const c = 30; 💥 Error again ❌ Why? Because `let` & `const` are also hoisted… BUT they live in something called: 👉 “Temporal Dead Zone” (TDZ) Translation: 🧠 “You can’t touch it before it’s declared” --- 💡 Simple Breakdown: ✔ `var` → hoisted + initialized as `undefined` ✔ `let` → hoisted but NOT initialized ✔ `const` → same as let (but must assign value) 💀 Real dev pain: Using `var`: 👉 “Why is this undefined?” Using `let`: 👉 “Why is this error?” JavaScript: 👉 “Figure it out yourself” 😎 💡 Takeaway: ✔ Avoid `var` (legacy behavior) ✔ Prefer `let` & `const` ✔ Understand hoisting = fewer bugs 👉 JS is not weird… You just need to know its secrets 😉 🔁 Save this before hoisting confuses you again 💬 Comment “TDZ” if this finally made sense ❤️ Like for more JS quirks #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
🤯 One of the most confusing concepts in JavaScript — 'this' keyword If you've worked with JavaScript, you’ve probably asked: 👉 “What exactly does ‘this’ refer to?” Here’s the simple rule: 👉 “this = Who called me?” Let’s understand with examples 👇 📌 1. Object Method const user = { name: "Vinay", greet() { console.log(this.name); } }; user.greet(); // Vinay 👉 Here, 'this' refers to the user object 📌 2. Normal Function function show() { console.log(this); } show(); // window (in browser) 👉 Here, 'this' refers to the global object 📌 3. Arrow Function const obj = { name: "Vinay", greet: () => { console.log(this.name); } }; obj.greet(); // undefined 👉 Arrow functions don’t have their own 'this' 👉 They inherit it from the parent scope 📌 4. Event Listener button.addEventListener("click", function () { console.log(this); }); 👉 Here, 'this' refers to the clicked element 💥 Final Tip: 👉 “'this' is not about where it’s written, it’s about how it’s called.” Master this concept, and your JavaScript skills will level up 🚀 #JavaScript #WebDevelopment #Coding #DeveloperLife #Frontend #Programming #JSConcepts
To view or add a comment, sign in
-
-
🧠 Day 6 — Closures in JavaScript (Explained Simply) Closures are one of the most powerful (and frequently asked) concepts in JavaScript — and once you understand them, a lot of things start to click 🔥 --- 🔐 What is a Closure? 👉 A closure is when a function “remembers” variables from its outer scope even after that scope has finished executing. --- 🔍 Example: function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); // 1 counter(); // 2 --- 🧠 What’s happening? inner() still has access to count Even after outer() has finished execution This happens because of lexical scoping --- 🚀 Why Closures Matter ✔ Data privacy (like encapsulation) ✔ Used in callbacks & async code ✔ Foundation of React hooks (useState) ✔ Helps create reusable logic --- ⚠️ Common Pitfall for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } 👉 Output: 3 3 3 ✔ Fix: for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } --- 💡 One-line takeaway: 👉 “A closure remembers its outer scope even after it’s gone.” --- If you’re learning JavaScript fundamentals, closures are a must-know — they show up everywhere. #JavaScript #Closures #WebDevelopment #Frontend #100DaysOfCode 🚀
To view or add a comment, sign in
-
🚀 JavaScript Event Loop — The Concept That Confuses (Almost) Everyone If you’ve ever wondered: 👉 Why does Promise run before setTimeout? 👉 How JavaScript handles async code while being single-threaded? Let’s break it down visually 👇 🧠 JavaScript Memory Model: • Call Stack → Executes functions (one at a time) • Heap → Stores objects, closures, data ⚙️ Behind the Scenes: JavaScript doesn’t handle async tasks alone — it uses: • Web APIs (browser / Node runtime) • Queues to schedule execution 📦 Queues Explained: 🔥 Microtask Queue (HIGH PRIORITY) → Promise.then, queueMicrotask 🕒 Macrotask Queue (LOW PRIORITY) → setTimeout, setInterval, events 🔁 Event Loop Flow: 1. Execute Call Stack 2. When stack is empty → Run ALL Microtasks 3. Then execute ONE Macrotask 4. Repeat 💡 Example: console.log("Start"); setTimeout(() => console.log("Timeout"), 0); Promise.resolve().then(() => console.log("Promise")); console.log("End"); 👉 Output: Start → End → Promise → Timeout ⚠️ Pro Tip (Interview Gold) Microtasks can starve macrotasks if continuously added — meaning setTimeout might never run! 🎯 Golden Rule to Remember: 👉 Call Stack > Microtasks > Macrotasks 🧠 Think of it like this: 👨🍳 Call Stack = Chef (works on one dish) ⭐ Microtasks = VIP orders (served first) 📋 Macrotasks = Normal orders (served later) If this helped you understand the Event Loop better, drop a 👍 or share with someone preparing for frontend interviews! #JavaScript #Frontend #WebDevelopment #ReactJS #InterviewPrep #Programming
To view or add a comment, sign in
-
-
Have you ever struggled with timing in your JavaScript code? Understanding setTimeout and setInterval can transform how you handle asynchronous tasks. ────────────────────────────── Mastering setTimeout and setInterval Patterns Unlock the potential of setTimeout and setInterval in your JavaScript projects. #javascript #settimeout #setinterval #asynchronous #codingtips ────────────────────────────── Key Rules • Use setTimeout for one-time delays. • Use setInterval for repeated execution at intervals. • Clear intervals with clearInterval to prevent memory leaks. 💡 Try This setInterval(() => { console.log('This will run every second!'); }, 1000); setTimeout(() => { clearInterval(myInterval); console.log('Stopped the interval!'); }, 5000); ❓ Quick Quiz Q: What method would you use to execute a function repeatedly? A: setInterval. 🔑 Key Takeaway Mastering these timing functions can lead to cleaner and more efficient code! ────────────────────────────── Tests keep failing after tiny UI changes and your team wastes hours debugging selectors. Release confidence drops when flaky E2E results hide real regressions.
To view or add a comment, sign in
-
🔍 JavaScript Behavior You Might Have Seen (Promise Chaining) You write this: Promise.resolve(1) .then((res) => { console.log(res); return res + 1; }) .then((res) => { console.log(res); return res + 1; }); 👉 Output: 1 2 Now try this 👇 Promise.resolve(1) .then((res) => { console.log(res); }) .then((res) => { console.log(res); }); 👉 Output: 1 undefined 🤯 Same chain… different result… why? This happens because of Promise Chaining 📌 What is Promise Chaining? 👉 It’s the process of passing the result from one .then() to the next 📌 What’s happening here? ✔ If you return a value: 👉 It goes to the next .then() ✔ If you don’t return anything: 👉 undefined is passed So this: .then((res) => { console.log(res); }) 👉 is actually: .then((res) => { console.log(res); return undefined; }) 📌 Important rule: 👉 Every .then() returns a new Promise 📌 Bonus case 👇 .then((res) => { return Promise.resolve(res + 1); }) 👉 Next .then() waits for it automatically 💡 Takeaway: ✔ Return value → passed to next .then() ✔ No return → undefined ✔ Returning Promise → waits automatically 👉 Promise chain is all about “what you return” 🔁 Save this for later 💬 Comment “promise” if this clicked ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
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