🚀 Understanding Hoisting in JavaScript Ever wondered how you can use a variable or function before it’s declared? 🤔 That’s because of Hoisting! In JavaScript, hoisting means that variable and function declarations are moved to the top of their scope during the compile phase — before the code actually runs. 🧠 Example: greet(); // ✅ Works! function greet() { console.log("Hello, World!"); } Here, the function greet() is hoisted to the top — that’s why you can call it even before it’s defined. But be careful with variables 👇 console.log(x); // ❌ undefined var x = 10; Variables declared with var are hoisted but not initialized, so they exist but hold undefined. However, variables declared with let and const are also hoisted but stay in the Temporal Dead Zone (TDZ) until they’re actually declared. 📌 In short: Functions → hoisted with their definitions ✅ var → hoisted but undefined ⚠️ let & const → hoisted but inaccessible until declared 🚫 #javascript #frontend #webdevelopment
How JavaScript Hoisting Works: Functions, Var, Let, Const
More Relevant Posts
-
🤔 What do you guys think — do let and const allow hoisting in JavaScript? Most people would say no, but the real answer is... Yes, they do! 💡 Both let and const are hoisted in JavaScript — but not in the same way as var. Here’s the catch 👇 When the JavaScript engine runs your code, it creates a Execution context — this includes a separate memory space for variables declared with let and const. Unlike var, which gets initialized with undefined in the global memory, let and const are placed in a different memory (block scope) but not initialized immediately. That’s why if you try to access them before their declaration, you’ll get a ReferenceError ⚠ and not undefined. This time between hoisting and initialization is called the 𝐓𝐞𝐦𝐩𝐨𝐫𝐚𝐥 𝐃𝐞𝐚𝐝 𝐙𝐨𝐧𝐞 (𝐓𝐃𝐙) . --- 💡 Example console.log(x); // ReferenceError ❌ let x = 5; Here, x is hoisted but not yet initialized — it’s in the Temporal Dead Zone from the start of the block until its declaration line. --- 🧠 In Simple Terms ✅ var → hoisted & initialized with undefined ⚠ let / const → hoisted but not initialized → Temporal Dead Zone 💬 Accessing them before declaration → ReferenceError --- ✨ Quick Tip To avoid TDZ issues: > Always declare your variables at the top of their scope before using them. --- 💬 JavaScript hoisting can be tricky — it’s not about whether variables are lifted, but when and where they get initialized in memory. #JavaScript #WebDevelopment #Frontend #LearningJourney #TemporalDeadZone #LexicalEnvironment #Hoisting #JSConcepts
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
-
Many of us are familiar with how var is hoisted in JavaScript, leading to potential confusion. But what about let and const? They are also hoisted, but with a critical difference that introduces the Temporal Dead Zone (TDZ)! What is Hoisting with let and const? 🤔 Hoisting is a phenomenon that allows us to access functions and variables before we initialize them. Contrary to popular belief, let and const declarations are indeed hoisted just like var and function declarations. However, the crucial difference lies in their memory allocation: unlike var, which is initialized with the placeholder "undefined" during the memory allocation phase (and is attached to the global object), let and const are also allocated memory, but this is stored in a separate memory space from the global one. We cannot access this separate memory space before assigning a value to let or const. This state of inaccessibility creates the Temporal Dead Zone (TDZ), which persists until the let and const variables are initialized. The Temporal Dead Zone (TDZ) ⏳ The Temporal Dead Zone is the period of time from when let and const are hoisted until they are initialized with some value. If you try to access a let or const within its TDZ, JavaScript will throw a "ReferenceError" because the variable exists but hasn't reached its initialization point. 💡 The Key Takeaway: -> Hoisting allows us to access functions and variables before initialization. -> TDZ is the time before the let and const variables are assigned a value. #javascript #reactjs #webdev
To view or add a comment, sign in
-
🧠 Understanding Block Statements and Lexical Scope in JavaScript When I first started coding in JavaScript, I didn’t really pay attention to where I declared my variables — as long as the code ran, I was happy 😅. But once I began working on bigger projects, I realized scope and block behavior can make or break your code’s predictability. Here’s the thing: A block statement is simply the part inside { } — it could be inside an if, a for, or even just a standalone block. Example: { let message = "Hello world"; console.log(message); } console.log(message); // ❌ ReferenceError What’s happening? Because of lexical scoping, variables declared with let and const only exist within the block they were defined in. Meanwhile, var ignores that and leaks out — which is one reason modern JS avoids it. Understanding how lexical scope works helps prevent weird bugs and keeps your functions predictable. It’s one of those quiet fundamentals that makes your JavaScript more intentional and less chaotic. Have you ever been bitten by a var variable leaking out of a block before? 😅 #JavaScript #WebDevelopment #Frontend #CleanCode #JSFundamentals
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
-
🚀 Memorization with Closures — The Smart Side of JavaScript Have you ever wondered how JavaScript can “remember” something — even after a function has finished executing? 🤔 That’s the magic of closures — a function remembering its lexical scope even when it’s executed outside of it. Now, combine this power with memorization, and you get a performance booster that saves repeated computation! 💡 Imagine this: You have a function that takes time to compute something (like fetching data or calculating a large factorial). Instead of recalculating every time, you cache the result using a closure — so the next call instantly returns the saved output. It’s like having a personal assistant who remembers your previous answers and gives them back instantly when asked again. ⚡ Closures enable that memory — they preserve state without needing global variables or complex structures. 🧠 In simple terms: > “Closures give your functions memory — and memorization teaches them to use it wisely.” Closures + Memorization = Efficiency ✨ If you’ve ever wondered how frameworks and libraries optimize repeated calls, look closer — closures are quietly doing the heavy lifting. #JavaScript #WebDevelopment #Closures #Performance #Frontend #ProgrammingTips
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 Core Concept: Hoisting Explained Ever wondered why you can call a variable before it’s declared in JavaScript? 🤔 That’s because of Hoisting — one of JavaScript’s most important (and often misunderstood) concepts. When your code runs, JavaScript moves all variable and function declarations to the top of their scope before execution. 👉 But here’s the catch: Variables (declared with var) are hoisted but initialized as undefined. Functions are fully hoisted, meaning you can call them even before their declaration in the code. 💡 Example: console.log(name); // undefined var name = "Ryan"; During compilation, the declaration var name; is moved to the top, but the assignment (= "Ryan") happens later — that’s why the output is undefined. 🧠 Key Takeaway: Hoisting helps JavaScript know about variables and functions before execution, but understanding how it works is crucial to avoid tricky bugs. #JavaScript #WebDevelopment #Frontend #ProgrammingConcepts #Learning #Hoisting #CodeTips
To view or add a comment, sign in
-
-
Did you know? In JavaScript var, let and const are all hoisted, but they behave differently. Most people think let and const are not hoisted because their behavior does not match var. In reality, they’re placed in a special zone called the Temporal Dead Zone (TDZ). Check out these points for better clarity: 1. var - Hoisted + initialized as undefined 2. let & const - Hoisted but not initialized (that’s why you get ReferenceError) 3. var - Function scoped 4. let & const - Block scoped 5. const - Must be initialized at declaration 6. All global var - live in window object 7. let & const - stored in a separate “Script” scope console.log(a) // reference error let a = 20; isn’t because it’s not hoisted, it' s because a is inside the TDZ. Once you understand this, the behavior of JavaScript stops feeling random. #javascript #frontenddevelopment #webdevelopment #learninginpublic
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