JavaScript Hoisting 🎭 At first, it feels like variables and functions magically “float” to the top of your script. But in reality, nothing is physically moving. I like to explain it using Reserved Seats. Imagine walking into a cinema. Before the first person enters, some seats are already reserved. But the people (the values) aren’t sitting there yet. That’s exactly how the JavaScript engine works during the Creation Phase: • It scans your code • It allocates memory for declarations • It reserves space before executing a single line Code in Action: console.log(movie); var movie = "Inception"; // Output: undefined Why? Because var movie reserved the seat during creation, but the value "Inception" arrived only when execution reached that line. What about let and const? They are hoisted too but they stay inside the Temporal Dead Zone (TDZ) until their declaration line is reached. Think of it like a reserved seat that stays locked until the owner arrives with the key. Try to use it too early, and JavaScript throws an error. Why This Matters in Real Projects • Debugging unexpected undefined values • Writing predictable code • Avoiding scope confusion • Understanding how JavaScript executes behind the scenes Hoisting isn’t magic — it’s JavaScript preparing the room before the party starts. Once you understand the Creation Phase, many “weird” behaviors finally make sense. #JavaScript #ReactJS #NodeJS #FrontendEngineer #OpentoWork #SoftwareDevelopment #FullStack #JavascriptDeveloper #ReactjsDeveloper #FrontEndDeveloper #FullstackDeveloper
JavaScript Hoisting Explained with Reserved Seats
More Relevant Posts
-
🚀 Understanding the JavaScript Event Loop (Simple Explanation) Ever wondered how JavaScript handles multiple tasks even though it’s single-threaded? 🤔 That’s where the Event Loop comes in! 👉 In simple terms: The Event Loop manages execution of code, handles async operations, and keeps your app running smoothly. 🔹 Key Components: Call Stack → Executes functions (one at a time) Web APIs → Handles async tasks (setTimeout, fetch, etc.) Callback Queue → Stores callbacks from async tasks Microtask Queue → Stores Promises (higher priority) Event Loop → Moves tasks to the Call Stack when it's free 🔹 Example: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); 👉 Output: Start End Promise Timeout 🔹 Why this output? "Start" → runs first (Call Stack) "End" → runs next Promise → goes to Microtask Queue (runs before callbacks) setTimeout → goes to Callback Queue (runs last) 💡 Key Insight: 👉 Microtasks (Promises) always execute before Macrotasks (setTimeout) 🔥 Mastering the Event Loop helps you write better async code and avoid unexpected bugs! #JavaScript #Frontend #WebDevelopment #Coding #InterviewPrep
To view or add a comment, sign in
-
⚡ 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
-
🚀 How JavaScript Works Behind the Scenes We use JavaScript every day… But have you ever thought about what actually happens when your code runs? 🤔 Let’s understand it in a simple way 👇 --- 💡 Step 1: JavaScript needs an Engine JavaScript doesn’t run on its own. It runs inside a JavaScript engine like V8 (Chrome / Node.js). 👉 Engine reads → understands → executes your code --- 💡 Step 2: Two Important Things When your code runs, JavaScript uses: 👉 Memory Heap → stores variables & functions 👉 Call Stack → executes code line by line --- 💡 Step 3: What happens internally? let name = "Aman"; function greet() { console.log("Hello " + name); } greet(); Behind the scenes: - "name" stored in Memory Heap - "greet()" stored in Memory Heap - function call goes to Call Stack - executes → removed from stack --- 💡 Step 4: Single Threaded Meaning JavaScript can do only one task at a time 👉 One Call Stack 👉 One execution at a time --- ❓ But then… how does async work? (setTimeout, API calls, promises?) 👉 That’s handled by the runtime (browser / Node.js) More on this in next post 👀 --- 💡 Why this matters? Because this is the base of: - Call Stack - Execution Context - Closures - Async JS --- 👨💻 Starting a series to revisit JavaScript from basics → advanced with focus on real understanding Follow along if you want to master JS 🚀 #JavaScript #JavaScriptFoundation #WebDevelopment #FrontendDevelopment #Coding #SoftwareEngineer #Tech
To view or add a comment, sign in
-
-
🚀 JavaScript Output Prediction Challenge What will be the output? 🤔 💡 Important Behaviour: 👉 JavaScript executes code line by line 👉 The very first line throws the following: ❌ ReferenceError: a is not defined So in reality, the programme stops immediately and nothing else runs. 📌 Now, let’s understand what would happen inside the function (ignoring the first error): 👉 Before execution, JS does Hoisting (memory creation phase) Inside the function: var a → hoisted and initialized as undefined let b → hoisted but kept in Temporal Dead Zone (TDZ) (not accessible yet) 👉 Execution phase: "1:" → undefined (Because 'a' exists but not assigned yet) "2:" → ❌ ReferenceError (because b is in TDZ) After assignment: a = 10 b = 20 "3:" → 10 "4:" → 20 🔥 Core Concepts: JS has 2 phases → Memory Creation + execution. var → hoisted + usable as undefined let/const → hoisted but blocked by TDZ 💬 If you got this right, your JS fundamentals are solid 👇 #JavaScript #Hoisting #Frontend #CodingChallenge #WebDevelopment
To view or add a comment, sign in
-
-
🔍 JavaScript Behavior You Might Have Seen (Promises) You write this: console.log("Start"); setTimeout(() => { console.log("Async Task"); }, 1000); console.log("End"); 👉 Output: Start End Async Task Why didn’t it wait? This is where Promises come in 📌 What is a Promise? 👉 A Promise is an object that represents the result of an synchronous operation (success or failure) 📌 Why do we need it? Before Promises: 👉 Nested callbacks (callback hell) 👉 Hard to read 👉 Hard to debug 📌 Example with Promise 👇 const promise = new Promise((resolve, reject) => { setTimeout(() => { resolve("Task Done"); }, 1000); }); promise.then((res) => { console.log(res); }); 👉 Output after 1s: Task Done 📌 Promise States: ✔ Pending → initial state ✔ Fulfilled → success (resolve) ✔ Rejected → failure (reject) 💡 Takeaway: ✔ Promises handle async operations ✔ Cleaner than callbacks ✔ Foundation for async/await 👉 If you understand Promises, async JavaScript becomes much easier 🔁 Save this for later 💬 Comment “promise” if this made sense ❤️ Like for more JavaScript deep dives #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
🧠 Day 12 — Prototypal Inheritance in JavaScript (Simplified) JavaScript doesn’t use classical inheritance like other languages — it uses prototypes. --- 🔍 What is Prototypal Inheritance? 👉 Objects in JavaScript can inherit properties and methods from other objects --- 📌 Example: const animal = { eats: true }; const dog = Object.create(animal); dog.barks = true; console.log(dog.eats); // true console.log(dog.barks); // true --- 🧠 What’s happening? dog doesn’t have eats JavaScript looks up the prototype chain Finds eats inside animal 👉 This is called prototype chaining --- 🔗 Prototype Chain 👉 If a property is not found: JS looks in the object Then its prototype Then prototype’s prototype Until null --- 🚀 Why it matters ✔ Memory efficient (shared methods) ✔ Core concept behind JS objects ✔ Used in classes internally --- 💡 One-line takeaway: 👉 “Objects can inherit from other objects using prototypes.” --- Understanding this makes concepts like classes and this much easier. #JavaScript #Prototypes #WebDevelopment #Frontend #100DaysOfCode
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
-
🧠 JavaScript Execution Context Explained Simply Ever wondered what actually happens when JavaScript runs your code? Behind the scenes, everything runs inside something called an Execution Context. Here’s a simple way to understand it 👇 🔹 What is Execution Context? It’s the environment where JavaScript code is evaluated and executed. There are mainly two types: • Global Execution Context • Function Execution Context 🔹 How JavaScript runs code Every execution context has 2 phases: 1️⃣ Creation Phase • Variables are set up • Functions are stored in memory • this is determined 2️⃣ Execution Phase • Code runs line by line • Values are assigned • Functions are executed 🔹 Call Stack JavaScript uses a call stack to manage execution. • When a function is called → it’s pushed to the stack • When it finishes → it’s popped out This is why JavaScript is single-threaded and synchronous by default. 🔹 Why this matters Understanding execution context helps you: ✅ understand hoisting better ✅ debug issues more effectively ✅ write predictable code 💡 One thing I’ve learned: When you understand how JavaScript runs internally, many “confusing” behaviors start making sense. Curious to hear from other developers 👇 Which JavaScript concept helped you the most in improving your fundamentals? #javascript #frontenddevelopment #webdevelopment #reactjs #softwareengineering #developers
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
-
🚀 JavaScript Event Loop Explained (A Must-Know Concept) If you've ever wondered why setTimeout(fn, 0) doesn’t run immediately or how JS handles async tasks while being single-threaded — this is where the Event Loop comes in. Let’s break it down 👇 🧠 1. JavaScript is Single-Threaded JS runs one thing at a time using a Call Stack. Functions are pushed → executed → popped Only synchronous code runs here 🌐 2. Web APIs (Browser Magic) When JS encounters async operations: setTimeout, fetch, DOM events 👉 They are handled outside JS by Web APIs Once done, they don’t go to the stack directly… 📬 3. Queues (Where async waits) There are 2 types of queues: 🔹 Microtask Queue (High Priority) Promise.then() queueMicrotask() MutationObserver 🔸 Macrotask Queue (Low Priority) setTimeout() setInterval() DOM events 🔄 4. Event Loop (The Brain) The Event Loop keeps checking: 1️⃣ Is Call Stack empty? 2️⃣ Run ALL Microtasks 🟢 3️⃣ Then run ONE Macrotask 🟡 4️⃣ Repeat 🔁 💡 Example: console.log(1); setTimeout(() => console.log(2), 0); Promise.resolve().then(() => console.log(3)); console.log(4); 📌 Output: 👉 1 → 4 → 3 → 2 🔥 Why? 1, 4 → synchronous → run first 3 → microtask → higher priority 2 → macrotask → runs last ⚡ Pro Tips ✔ Microtasks always run before macrotasks ✔ Even setTimeout(fn, 0) is NOT immediate ✔ Too many microtasks can block UI (⚠️ starvation) 🎯 Why You Should Care Understanding the Event Loop helps you: Write better async code Debug tricky timing issues Ace JavaScript interviews 💼 💬 If this clarified things, drop a 👍 or comment your doubts — happy to help! #JavaScript #WebDevelopment #Frontend #NodeJS #Coding #Programming #SoftwareEngineering
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