💡 Have you ever wondered why these two JavaScript loops behave differently? for (let i = 0; i < 10; i++) { setTimeout(() => console.log(i), 0); } for (var i = 0; i < 10; i++) { setTimeout(() => console.log(i), 0); } It’s because of the default behavior of how let and var work in JavaScript. If you’re familiar with JavaScript, you may know that let is block-scoped, while var is function/global-scoped. In the case of let, since it’s block-scoped, it creates a new variable i and assigns a value to it during each iteration. So, each i points to a different memory location — kind of like a house with multiple rooms, and each room contains its own variable called i. That’s why it logs 0 to 9 after the wait is over. But in the case of var, since it’s function/global-scoped, the variable is created only once and points to the same memory location. So it logs 10 ten times. It’s similar to writing: var i; for (i = 0; i < 10; i++) { setTimeout(() => console.log(i), 0); } #Javascript #Frontend
Why JavaScript loops behave differently with let and var
More Relevant Posts
-
🧠 Why does let create a new closure in every loop iteration in JavaScript? Ever wondered why this works perfectly 👇 for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); } // Output: 0, 1, 2 …but this doesn’t 👇 for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); } // Output: 3, 3, 3 That’s not “compiler magic” — it’s actually defined in the ECMAScript specification itself. 📜 --- 📘 ECMA Definition From ECMA-262 §13.7.4.8 – Runtime Semantics: ForBodyEvaluation: > If the loop variable is declared with let or const, a new LexicalEnvironment is created for each iteration. The variable is copied (rebound) from the previous environment and used to evaluate the loop body in this new environment. --- 🔍 What This Means Every time the loop runs: JavaScript creates a new environment record (a fresh closure). The loop variable (i) is independent for that iteration. Each callback “remembers” its own copy of i. So effectively: var → single shared binding across all iterations. let / const → new closure per iteration. --- ✅ In short: let is not just about block scoping — it’s about creating predictable closures inside loops by design. #JavaScript #ECMAScript #Closures #Frontend #WebDevelopment #CodingTips #LearnInPublic
To view or add a comment, sign in
-
Arrow Functions vs Regular Functions in JavaScript ⚔️ They look similar, right? But under the hood, arrow functions and regular functions behave very differently — especially when it comes to this, arguments, and constructors. Let’s break it down 👇 1️⃣ 'this' Binding 👉 Regular functions have their own this — it depends on how the function is called. 👉 Arrow functions don’t have their own this; they inherit it from the enclosing scope. 💡 When to use which: • Use a regular function when you need dynamic this (methods, event handlers, etc.). • Use an arrow function when you want lexical this (callbacks, promises, or closures). 2️⃣ 'arguments' Object Regular functions get an implicit arguments object. Arrow functions don’t — they rely on rest parameters if you need access to arguments. 3️⃣ Constructors Regular functions can be used as constructors with new. Arrow functions cannot — they don’t have a prototype. 👉 Which one do you prefer using in your daily JavaScript code — and why? #JavaScript #NodeJS #Frontend #Backend #SoftwareEngineering #CleanCode #ArrowFunction #RegularFunction #SoftwareEngineer
To view or add a comment, sign in
-
🚀 How Closures Work in JavaScript — Explained Simply A closure is one of those concepts that seems confusing until it clicks. Here’s how I like to explain it 👇 A closure is created when a function remembers its lexical scope even after it’s executed outside that scope. function outer() { let counter = 0; return function inner() { counter++; console.log(counter); }; } const count = outer(); count(); // 1 count(); // 2 count(); // 3 Even though outer() has finished running, the inner() function still remembers the counter variable. That’s closure in action — the inner function “closes over” the variables from its parent scope. 💡 Real-world use cases: Data privacy (hiding variables) Function factories Maintaining state without global variables Once you understand closures, async JS and callbacks become much easier! 💪 #JavaScript #WebDevelopment #Closures #Frontend #CodingTips #JSDeveloper #LearnToCode
To view or add a comment, sign in
-
-
The Simple JS Experiment That Completely Changed How I See Constructors Most JavaScript developers learn constructors one way: create, initialize, return the instance. That’s the story. That’s what everyone teaches. But then recently I realized that story is missing something. Today I’m going to show you why constructors returning functions exist, what they actually enable, and why this weird pattern solves problems that rigid constructors just can’t touch. #javascript #typescript #web https://lnkd.in/d5n3x8TV Let’s get started with the interesting part.
To view or add a comment, sign in
-
🚀 JavaScript Hoisting Explained (Simply!) Hoisting means JavaScript moves all variable and function declarations to the top of their scope before code execution. If that definition sounds confusing, see this example 👇 console.log(a); var a = 5; Internally, JavaScript actually does this 👇 var a; // declaration is hoisted (moved up) console.log(a); a = 5; // initialization stays in place ✅ Output: undefined --- 🧠 In Short: > Hoisting = JS reads your code twice: 1️⃣ First, to register variables & functions 2️⃣ Then, to execute the code line by line --- 💡 Tip: var → hoisted & initialized as undefined let / const → hoisted but not initialized (stay in Temporal Dead Zone) --- #JavaScript #Hoisting #WebDevelopment #CodingTips #JSInterview #Frontend #React #100DaysOfCode
To view or add a comment, sign in
-
💡 Understanding var, let, and const in JavaScript — A Must for Every Developer! When writing JavaScript, knowing how variables behave is crucial for clean and bug-free code. Here’s a quick breakdown 👇 🔹 var Scope: Function-scoped Hoisted: Yes (initialized as undefined) Re-declaration: Allowed ⚠️ Can cause unexpected results due to hoisting and re-declaration. 🔹 let Scope: Block-scoped ({ }) Hoisted: Yes (but not initialized — Temporal Dead Zone) Re-declaration: ❌ Not allowed in same scope ✅ Preferred for variables that can change. 🔹 const Scope: Block-scoped Hoisted: Yes (not initialized — Temporal Dead Zone) Re-declaration / Re-assignment: ❌ Not allowed ✅ Use for constants and values that never change. 🔍 Example: { var a = 10; let b = 20; const c = 30; } console.log(a); // ✅ Works (function-scoped) console.log(b); // ❌ Error (block-scoped) console.log(c); // ❌ Error (block-scoped) 🧠 Pro tip: Always prefer let and const over var for predictable and safer code. ✨ Which one do you use most often — let or const? Let’s discuss 👇 #JavaScript #WebDevelopment #Frontend #CodingTips #ES6
To view or add a comment, sign in
-
🎯 JavaScript Scope — The Invisible Boundary of Your Code! Have you ever written some JavaScript and suddenly got an error like: ❌ “variable is not defined” — even though you did define it? 😅 That’s the power (and sometimes the confusion) of Scope in JavaScript! --- 🧠 What is Scope? Scope simply means “where a variable is accessible in your code.” It determines which parts of your program can see or use a variable. Think of scope like a fence 🏡 — variables inside the fence can’t just wander outside unless they’re allowed to. --- 💡 Types of JavaScript Scope: 1️⃣ Global Scope 🌍 Variables declared outside any function or block. They can be used anywhere in your code. let name = "Azeez"; console.log(name); // Accessible everywhere 2️⃣ Function Scope 🧩 Variables declared inside a function are only visible inside that function. function greet() { let message = "Hello!"; console.log(message); // Works fine here } console.log(message); // ❌ Error! Not defined 3️⃣ Block Scope 🔒 Introduced with let and const — variables declared inside {} are only accessible within that block. if (true) { let food = "Pizza"; console.log(food); // Works } console.log(food); // ❌ Not accessible --- ⚡ Why Scope Matters: ✅ It prevents variable name conflicts ✅ It keeps your code organized and clean ✅ It improves memory management --- 💬 Quick Tip: Always use let and const instead of var — because var ignores block scope and can cause tricky bugs 🐛. --- 🚀 In short: Scope defines where your variables live and how far they can travel. Keep them in their lane, and your code will stay clean and bug-free! 😎 #codecraftbyaderemi #webdeveloper #frontend #webdevelopment #javascript #webdev
To view or add a comment, sign in
-
-
Class vs. Function: What's the Difference in JS? There are two main ways to create objects, add methods, and organize processes like inheritance in JavaScript code — the “constructor function” (“classic function”) and the object style created with the class keyword. While they have some similarities, they also have important differences. Let's get to know the most important ones. 1. How to write it Function (constructor style) is a modern, updatable style that was widely used in the ES5 era. Class (ES6 style) is syntactically cleaner and more modern. 2. Hoisting and “strict mode” tags Function declarations are hoisted — that is, you can declare the function getUser() even before calling it in your code. Class declarations are not hoisted — they must be declared before calling it. Also, code inside a class actually always runs in “strict mode” — you don’t need to write a separate “use strict”. 3. Inheritance Inheritance using a constructor function is more difficult: you need to call Function.call(this, …), Object.create(), manually configure the prototype, etc. Inheritance using the class style is very simple: class Child extends Parent { … }, and you can call super() inside it. 4. Syntactic aspects and additional features Inside a class, you can use features such as static methods, constructors, and private fields (since ES2022). Inside a function constructor, these features must be implemented manually (for example, using a closure or Symbol for private fields). 5. When to choose which style? If you are working with legacy code or have a lot of manual configuration with “prototypes”, the constructor function style can be useful. If you want modern coding, simpler syntax, and easy inheritance, class is the way to go. It has also been noted that class is often preferred for readability when writing code with a team. #Frontend #JavaScript #ReactJS #VueJS #WebDeveloper
To view or add a comment, sign in
-
-
💡 var, let, and const — The Three Musketeers of JavaScript ⚔️ If you’ve ever felt confused about when to use var, let, or const… you’re not alone. Even JavaScript sometimes forgets 😅 Let’s break it down like friends who share the same coffee machine ☕👇 ⸻ 🧓 var — The Old Guy from 1995 “I’ve seen things… global scope, function scope… chaos.” var name = "John"; if (true) { var name = "Doe"; console.log(name); // Doe } console.log(name); // Doe 😬 🧠 var doesn’t care about blocks. It’s function-scoped, gets hoisted, and often causes unexpected overwrites. 👉 Use only if you’re writing code for Internet Explorer 6 (please don’t 😂). ⸻ 🧑💻 let — The Responsible Adult “I respect boundaries.” let fruit = "Apple"; if (true) { let fruit = "Mango"; console.log(fruit); // Mango } console.log(fruit); // Apple ✅ 🧠 let is block-scoped and doesn’t get initialized until it’s declared. Perfect for values that will change later. ⸻ 🧘♀️ const — The Calm Monk “Once decided, I never change.” const pi = 3.14; // pi = 3.14159 ❌ Error 🧠 const is also block-scoped, but you can’t reassign it. (However, you can still mutate objects 👇) const person = { name: "John" }; person.name = "Doe"; // ✅ Allowed ⸻ 💬 My rule of thumb: 🧠 Use const by default → switch to let when you have to change it → forget var exists. ⸻ ✨ What’s your most funny or painful var moment? Drop it below 👇 #JavaScript #WebDevelopment #Frontend #CodingHumor #ReactJS
To view or add a comment, sign in
-
-
“The Secret Behind JavaScript’s Magic — The Event Loop 🧠” When I first learned JavaScript, I used to wonder — how can it handle so many things at once even though it’s single-threaded? 🤔 The answer lies in one beautiful mechanism — The Event Loop. Here’s what actually happens behind the scenes 👇 1️⃣ JavaScript runs in a single thread — only one thing executes at a time. 2️⃣ But when something async happens (like setTimeout, fetch, or Promise), those tasks are offloaded to the browser APIs or Node.js APIs. 3️⃣ Once the main call stack is empty, the event loop takes pending callbacks from the task queue (or microtask queue) and pushes them back into the stack to execute. So while it looks like JavaScript is multitasking, it’s actually just scheduling smartly — never blocking the main thread. Example:- console.log("Start"); setTimeout(() => console.log("Inside Timeout"), 0); Promise.resolve().then(() => console.log("Inside Promise")); console.log("End"); Output:- Start End Inside Promise Inside Timeout Even though setTimeout was “0 ms”, Promises (microtasks) always run before timeouts (macrotasks). That’s the secret sauce 🧠💫 Understanding this single concept can help you debug async behavior like a pro. #JavaScript #EventLoop #Async #WebDevelopment #Coding
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