💛 𝗗𝗮𝘆 𝟮 — 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: 𝗩𝗮𝗿𝗶𝗮𝗯𝗹𝗲𝘀, 𝗦𝗰𝗼𝗽𝗲, 𝗮𝗻𝗱 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴 Today, I revisited one of the most confusing yet powerful concepts in JavaScript — 𝗵𝗼𝗶𝘀𝘁𝗶𝗻𝗴 and 𝘀𝗰𝗼𝗽𝗶𝗻𝗴. 🧠 💡 𝗖𝗼𝗻𝗰𝗲𝗽𝘁: JavaScript moves all declarations to the top of their scope during compilation — this is known as hoisting. However, the behavior differs based on whether you use var, let, const, or functions. 💻 𝗖𝗼𝗱𝗲 𝗦𝗻𝗶𝗽𝗽𝗲𝘁: console.log(a); // undefined (hoisted) var a = 10; console.log(b); // ❌ ReferenceError (in TDZ) let b = 20; sayHello(); // ✅ Works — function declarations are hoisted function sayHello() { console.log("Hello from a hoisted function!"); } // ❌ Error: sayHi is not a function sayHi(); var sayHi = function () { console.log("Hi from function expression!"); }; 🧩 𝗘𝘅𝗽𝗹𝗮𝗻𝗮𝘁𝗶𝗼𝗻: 0. var is hoisted and initialized with undefined. 1. let and const are hoisted but stay uninitialized in the temporal dead zone (TDZ). 2. Function declarations are fully hoisted, so you can call them before defining. 3. Function expressions (especially when assigned to var) behave like variables — hoisted but not initialized. 📈 𝗦𝗰𝗼𝗽𝗲 𝗪𝗶𝘀𝗱𝗼𝗺: var → function scope let & const → block scope Functions → create their own local scope 🔥 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: Understanding how JavaScript creates and executes contexts will help you debug faster and think more like the JS engine itself. #JavaScript #100DaysOfCode #Hoisting #Scope #Functions #FrontendDevelopment #LearningEveryday
"Explaining JavaScript Hoisting and Scope"
More Relevant Posts
-
🚀 The JavaScript “Gotcha” That Confuses Even Experienced Devs 😅 Let’s look at this classic head-scratcher 👇 var x = 1; function test() { console.log(x); // 🤔 What prints here? var x = 2; } test(); // Output? Most people expect 1, but the actual output is undefined ⚡ 💡 Why? When JavaScript executes this code, it doesn’t run top-to-bottom linearly. It first creates an execution context for test(). During that setup phase: The declaration var x inside test() is hoisted to the top. It’s initialized with the value undefined. This local x shadows the global one — even before assignment happens. So when console.log(x) runs, JS finds a local x (which is still undefined) and stops there. The global x = 1 is ignored completely. Now, let’s tweak one small line 👇 var x = 1; function test() { console.log(x); // No local var } test(); // ✅ Output → 1 Here, there’s no local declaration, so JS walks up the scope chain and uses the global x. 🧠 Key Takeaway In JavaScript: > “What matters is where a variable is declared, not where it’s called.” Hoisting + scope can easily cause unexpected undefined values — especially in legacy var code. ⚡ Pro Tip Prefer let or const — they’re block-scoped and avoid this trap entirely 👇 let x = 1; function test() { console.log(x); // ReferenceError ❌ (due to Temporal Dead Zone) let x = 2; } The TDZ ensures you don’t accidentally use variables before they’re initialized. 💬 Have you ever lost time debugging a “weird undefined”? Share your favorite JavaScript scope/hoisting gotcha below 👇 👉 Follow Rahul R Jain for daily deep dives into how JavaScript really works under the hood. #JavaScript #WebDevelopment #FrontendDevelopment #CodingTips #AsyncJS #Hoisting #Scope #InterviewPreparation #TechEducation #LearnToCode #WebEngineer #CodeNewbie #RahulJain
To view or add a comment, sign in
-
🧩 Undefined vs Null 🤔 ✨ When there’s no existence, it’s Undefined, whereas emptiness exists by choice, it’s Null. 🔹 undefined → When a variable is declared but not assigned by the user, JavaScript itself assigns the value undefined by default. let a; console.log(a); // undefined 🧠 It means: “No value exists yet — JavaScript couldn’t find one.” 🔹 null → When a variable is explicitly assigned by the user to represent emptiness, it holds the value null. let b = null; console.log(b); // null 💡 It means: “The developer intentionally set this to nothing.” ⚙️ Type check curiosity typeof null; // "object" ❗ (a known JavaScript bug) typeof undefined; // "undefined" 🚫 Falsy values Both are falsy during condition checks 👇 if (!undefined && !null) console.log('Falsy values!'); 🎯 In short: 🟠 undefined → Not assigned by the user → JavaScript assigns it automatically. 🟣 null → Explicitly assigned by the user → JavaScript doesn’t assign it. 🔖 Hashtags #JavaScript #WebDevelopment #Frontend #CodingTips #LearnToCode #JSBasics #WebDevCommunity #JavaScriptTips #CodeNewbie #DeveloperInsights
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
-
🔧 Deep Dive into JavaScript Variables Today, I explored a core JavaScript concept with deeper technical insight — Variable Declarations. JavaScript provides three keywords for declaring variables: var, let, and const, each with unique behavior related to scope, mutability, and hoisting. 🧠 Technical Insights I Learned ✔️ Execution Context & Memory Allocation During the creation phase, JavaScript allocates memory for variables. var is hoisted and initialized with undefined. let and const are hoisted but remain in the Temporal Dead Zone (TDZ) until execution reaches their line. ✔️ Scope Differences var → function-scoped, leaks outside blocks, may cause unintended overrides let & const → block-scoped, making them safer for predictable behavior ✔️ Mutability & Reassignment var and let allow reassignment const does not allow reassignment, but its objects and arrays remain mutable ✔️ Best Practices (ES6+) Prefer const for values that should not change Use let for variables that require reassignment Avoid var in modern codebases due to its loose scoping and hoisting behavior ✔️ Cleaner Code Through ES6 The introduction of let and const significantly improved variable handling, reduced bugs caused by hoisting, and enabled more structured, modular JavaScript. Mastering these low-level behaviors helps build stronger foundations for understanding execution context, closures, event loops, and advanced JavaScript patterns. Grateful to my mentor Sudheer Velpula sir for guiding me toward writing technically sound and modern JavaScript. 🙌 #JavaScript #ES6 #Variables #FrontendDevelopment #CleanCode #ProgrammingFundamentals #WebDevelopment #TechnicalLearning #CodingJourney #JSConcepts #DeveloperCommunity
To view or add a comment, sign in
-
-
🧠 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
-
“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
-
Understanding the difference between JavaScript's forEach() and map() is crucial for writing efficient code. Both iterate over arrays, but with key differences: forEach() runs a function on each array element without returning a new array. It’s great for side effects like logging or updating UI. map() transforms each element and returns a new array, perfect for data transformation without mutating the original array. Use forEach() when you want to perform actions without changing the array, and map() when you want to create a new array from existing data. Quick example: javascript const numbers = [1, 2, 3]; numbers.forEach(num => console.log(num * 2)); // Just logs the result const doubled = numbers.map(num => num * 2); // Returns [2, 4, 6] Master these to write cleaner, more expressive JavaScript! #JavaScript #WebDevelopment #ProgrammingTips #Coding
To view or add a comment, sign in
-
Have you ever wondered why a setTimeout call even with zero delay executes after a Promise.resolve().then()? Many developers assume JavaScript runs strictly line-by-line, but the reality involves a hidden orchestrator that manages asynchronous priorities: the Event Loop. Understanding the Event Loop isn't just theory; it's fundamental to writing fast, reliable, and performant web applications that avoid blocking the main thread. In my new article on Medium, I break down a simple code snippet to precisely explain the mechanics of the Microtask and Macrotask Queues and reveal why Promises get absolute priority. Click the link below to dive in and uncover the secret behind this non-intuitive execution order: [ https://lnkd.in/dEFGEXSC] #Javascript_EventLoop #Microtasks #Macrotasks
To view or add a comment, sign in
-
Understanding Microtasks & Macrotasks in JavaScript — The Event Loop Secret! Ever wondered how JavaScript handles async operations like Promises, timeouts, or fetch calls? 🤔 It’s all managed by the Event Loop, which uses two main types of queues — Microtasks and Macrotasks. 💡 Definition: Microtasks: Tasks that run immediately after the current script, before any rendering. 👉 Includes Promises, MutationObservers, and queueMicrotask(). Macrotasks: Tasks that run after the current event loop cycle, often with a small delay. 👉 Includes setTimeout, setInterval, setImmediate, and I/O tasks. 🧩 Example: console.log("1️⃣ Script start"); setTimeout(() => console.log("4️⃣ setTimeout (Macrotask)"), 0); Promise.resolve().then(() => console.log("3️⃣ Promise (Microtask)")); console.log("2️⃣ Script end"); ✅ Output: 1️⃣ Script start 2️⃣ Script end 3️⃣ Promise (Microtask) 4️⃣ setTimeout (Macrotask) Notice how Promise (Microtask) runs before setTimeout — that’s how the event loop prioritizes microtasks 🚀 ⚙️ Why It’s Important: ✅ Helps you understand async behavior ✅ Prevents performance issues ✅ Explains why Promises run before timers 🔖 #JavaScript #EventLoop #Microtasks #Macrotasks #AsyncProgramming #WebDevelopment #Frontend #JSConcepts #CodingTips #100DaysOfCode #KishoreLearnsJS #DeveloperJourney #WebDevCommunity
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
Great insights that every JS developer should know!