What will happen if you call a variable before initialization? 🤔 That is called Hoisting 👉 "JavaScript moves declarations to the top of their scope before execution" Sounds confusing? Let’s break it down 👇 When you create variables or functions, JavaScript runs your code in 2 phases: 1️⃣ Memory Creation Phase Before execution, JavaScript scans your code and allocates memory Example (mentally): var a → undefined let b → uninitialized (Temporal Dead Zone) 2️⃣ Execution Phase Now JavaScript runs your code line by line 👉 If you access variables before initialization: var → returns undefined let / const → ReferenceError Why does this happen? Because: var is initialized with undefined in memory let and const are hoisted but stay in the Temporal Dead Zone (TDZ) until the line where they are declared Simple way to remember: var => “exist, but don’t have a value yet” let / const => “Don’t touch before declaration” ⚡ Bonus: Function declarations are fully hoisted, so you can call them before defining them Curious how functions behave in hoisting? 🤔 Go Google function vs function expression in JavaScript — it’ll surprise you 👀 That’s hoisting in JavaScript 🚀 #javascript #webdevelopment #coding #frontend #learninpublic #hoisting
JavaScript Hoisting Explained
More Relevant Posts
-
⚡ Day 7 — JavaScript Event Loop (Explained Simply) Ever wondered how JavaScript handles async tasks while being single-threaded? 🤔 That’s where the Event Loop comes in. --- 🧠 What is the Event Loop? 👉 The Event Loop manages execution of code, async tasks, and callbacks. --- 🔄 How it works: 1. Call Stack → Executes synchronous code 2. Web APIs → Handle async tasks (setTimeout, fetch, etc.) 3. Callback Queue / Microtask Queue → Stores callbacks 4. Event Loop → Moves tasks to the stack when it’s empty --- 🔍 Example: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); --- 📌 Output: Start End Promise Timeout --- 🧠 Why? 👉 Microtasks (Promises) run before macrotasks (setTimeout) --- 🔥 One-line takeaway: 👉 “Event Loop decides what runs next in async JavaScript.” --- If you're learning async JS, understanding this will change how you debug forever. #JavaScript #EventLoop #WebDevelopment #Frontend #100DaysOfCode 🚀
To view or add a comment, sign in
-
Ever written JavaScript that *shouldn’t* work… but somehow does? 🤯 I remember staring at my screen thinking, “Did JS just ignore my logic?” Here’s the problem 👇 JavaScript has this hidden behavior called **hoisting**. It moves declarations (not values) to the top of the scope *before execution*. Sounds helpful… until it silently breaks your expectations. Here’s the insight 💡 * `var` gets hoisted and initialized as `undefined` * `let` & `const` are hoisted but stay in a “temporal dead zone” 🚫 * Functions? Fully hoisted — you can call them before defining! Example: ```js console.log(a); // undefined 😵 var a = 5; ``` Lesson learned 📌 JavaScript isn’t “weird” — it just follows rules we often ignore. Understanding hoisting = fewer bugs + cleaner logic. Now I always think: “What does JS see *before* running this?” 👀 If you’re diving deeper into JS concepts, I share more here 👉 https://webdevlab.org 🚀 Curious… have you ever been surprised by hoisting in your code? 😄 #JavaScript #WebDevelopment #Frontend #CodingTips #DevLife
To view or add a comment, sign in
-
-
🚀Day 30 — Scope Chain & Scope Types in JavaScript (Simplified) Understanding scope is one of the most important fundamentals in JavaScript 🚀 --- 🔍 What is Scope? 👉 Scope decides where variables can be accessed in your code In simple words: 👉 “Who can access what?” --- ⚡ Types of Scope 1. Global Scope 👉 Variables declared outside functions or blocks let name = "John"; function greet() { console.log(name); // accessible } --- 2. Function Scope 👉 Variables declared inside a function function test() { let age = 25; console.log(age); } console.log(age); // ❌ Error --- 3. Block Scope 👉 Variables declared with let and const inside {} if (true) { let city = "Delhi"; } console.log(city); // ❌ Error --- 🔗 What is Scope Chain? 👉 If JS can’t find a variable in current scope, it looks in the outer scope, then outer again… until global scope. This is called the Scope Chain --- 🚀 Why it matters ✔ Prevents variable conflicts ✔ Helps understand closures ✔ Improves debugging skills --- 💡 One-line takeaway: 👉 “JavaScript looks upward to find variables — that’s the scope chain.” --- Mastering scope makes closures, hoisting, and debugging much easier. #JavaScript #Scope #ScopeChain #WebDevelopment #Frontend #100DaysOfCode 🚀
To view or add a comment, sign in
-
🧠 Day 29 — Execution Context & Call Stack in JavaScript (Simplified) Ever wondered how JavaScript actually runs your code behind the scenes? 🤔 It all starts with Execution Context and the Call Stack 🚀 --- 🔍 What is Execution Context? 👉 It’s the environment where JavaScript code is executed There are mainly 2 types: 1. Global Execution Context → Created first 2. Function Execution Context → Created whenever a function is called --- 📌 Example function one() { console.log("One"); two(); } function two() { console.log("Two"); } one(); --- 🧠 What happens? 👉 JS creates Global Execution Context 👉 one() is pushed to Call Stack 👉 Inside one(), two() is pushed 👉 After execution, functions are popped out --- ⚡ Call Stack = LIFO 👉 Last In, First Out Global() ↓ one() ↓ two() Then: two() → removed one() → removed Global() stays --- 🚀 Why it matters ✔ Helps debug errors ✔ Understand recursion better ✔ Explains stack overflow issues --- 💡 One-line takeaway: 👉 “Execution Context creates the environment, Call Stack manages the order.” --- Once you understand this, debugging JavaScript becomes much easier. #JavaScript #ExecutionContext #CallStack #WebDevelopment #Frontend #100DaysOfCode 🚀
To view or add a comment, sign in
-
📚 Blog Series Update! Between projects and busy work hours, I spent some time this week working on Part 3 of my Rediscovering JavaScript series, and now I’m happy to share a new weekend read: Variables, Scope, and Memory 🚀 In this blog post, I explore some of the most important JavaScript fundamentals: 🔹 Primitive vs reference values 🔹 Scope and scope chain 🔹 Execution context 🔹 Memory management & garbage collection These topics may sound basic, but they explain many of the “why did this happen?” moments developers face while coding. 🔗 Part 3 Rediscovering JavaScript (Part 3): Variables, Scope, and Memory: https://lnkd.in/ek8CySJc 🔗Friend link: https://lnkd.in/e4ddDhSc ✨ For this journey, I’m using Professional JavaScript for Web Developers by Nicholas C. Zakas as my main guide. ☕ Wishing you a wonderful weekend and an enjoyable read with your coffee! #JavaScript #WebDevelopment #Frontend #Programming #SoftwareEngineering #DevTips #Medium
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
-
🚀 Promises vs Async/Await in JavaScript If you're working with asynchronous code in JavaScript, you’ve probably used both Promises and async/await. Here’s a simple way to understand the difference 👇 🔹 Promises -> Use .then() and .catch() for handling results. -> Chain-based approach. -> Can become harder to read with multiple steps. -> Good for handling parallel operations. Example: getUser(userId) .then(user => getOrders(user.id)) .then(orders => console.log(orders)) .catch(err => console.error(err)); 🔹 Async/Await -> Built on top of Promises (syntactic sugar) -> Cleaner, more readable (looks synchronous) -> Uses try...catch for error handling -> Easier to debug and maintain Example: async function run() { try { const user = await getUser(userId); const orders = await getOrders(user.id); console.log(orders); } catch (err) { console.error(err); } } 💡 Key Takeaway: Both do the same job, but async/await makes your code cleaner and easier to understand, especially as complexity grows. #JavaScript #WebDevelopment #AsyncProgramming #CodingTips
To view or add a comment, sign in
-
🚨 JavaScript Gotcha: When 0 Actually Matters One of the most subtle bugs in JavaScript comes from using the logical OR (||) for default values. const timeout = userTimeout || 3000; Looks fine… until userTimeout = 0. 👉 JavaScript treats 0 as falsy, so instead of respecting your value, it silently replaces it with 3000. 💥 Result? Unexpected behavior. ✅ The Fix: Use Nullish Coalescing (??) const timeout = userTimeout ?? 3000; This only falls back when the value is null or undefined — not when it’s 0. 💡 When does 0 actually matter? ⏱️ Timeouts & delays → 0 can mean run immediately 📊 Counters & stats → 0 is a valid value, not “missing” 💰 Pricing / discounts → Free (0) ≠ undefined 🎚️ Sliders / configs → Minimum values often start at 0 🧠 Rule of thumb: Use || when you want to catch all falsy values (0, "", false, etc.) Use ?? when you only want to catch missing values (null, undefined) ⚡ Small operator. Big difference. Cleaner logic. #reactjs,#nodejs #JavaScript #WebDevelopment #CleanCode #Frontend #ProgrammingTips #DevTips #CodeQuality #SoftwareEngineering
To view or add a comment, sign in
-
-
Most people don’t understand the JavaScript Event Loop. So let me explain it in the simplest way possible: JavaScript is single-threaded. It can only do ONE thing at a time. It uses something called a call stack → basically a queue of things to execute. Now here’s where it gets interesting: When async code appears (like promises or setTimeout), JavaScript does NOT execute it right away. It sends it away to the Event Loop and then keeps running what’s in the call stack. Only when the call stack is EMPTY… the Event Loop starts pushing async tasks back to be executed. Now look at the code in the image. What do you think runs first? Actual output: A D C B Why? Because not all async is equal: Promises (microtasks) → HIGH priority setTimeout (macrotasks) → LOW priority So the Event Loop basically says: “Call stack is empty? cool… let me run all promises first… then I handle setTimeout” If you get this, async JavaScript stops feeling random. #javascript #webdevelopment #frontend #reactjs #softwareengineering
To view or add a comment, sign in
-
-
🧠 JavaScript Hoisting Explained Simply Hoisting is one of those JavaScript concepts that can feel confusing — especially when your code behaves unexpectedly. Here’s a simple way to understand it 👇 🔹 What is Hoisting? Hoisting means JavaScript moves declarations to the top of their scope before execution. But there’s a catch 👇 🔹 Example with var console.log(a); var a = 10; Output: undefined Why? Because JavaScript internally treats it like: var a; console.log(a); a = 10; 🔹 What about let and const? console.log(b); let b = 20; This throws a ReferenceError. Because "let" and "const" are hoisted too — but they stay in a “temporal dead zone” until initialized. 🔹 Function hoisting Functions are fully hoisted: sayHello(); function sayHello() { console.log("Hello"); } This works because the function is available before execution. 🔹 Key takeaway • "var" → hoisted with "undefined" • "let/const" → hoisted but not initialized • functions → fully hoisted 💡 One thing I’ve learned: Many “weird” JavaScript bugs come from not understanding hoisting properly. Curious to hear from other developers 👇 Did hoisting ever confuse you when you started learning JavaScript? #javascript #frontenddevelopment #webdevelopment #reactjs #softwareengineering #developers
To view or add a comment, sign in
-
More from this author
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