Understood Hoisting in a much deeper way — not just definition, but what actually happens inside the JavaScript engine 👇 🧸 Imagine JavaScript like a teacher in a classroom Before teaching, the teacher prepares a register (memory) and writes all names first. 👉 JavaScript does the same thing before running code. 🧠 Behind the scenes (Real Concept): JavaScript runs in 2 phases: 1️⃣ Memory Creation Phase 2️⃣ Execution Phase ⚙️ During Memory Creation Phase: JavaScript creates something called an Execution Context (inside the Call Stack) Inside it, memory is allocated: 1- var → stored as undefined 2- let & const → stored but not initialized (Temporal Dead Zone) 3- functions → stored with full definition 💡 Example: console.log(a); var a = 10; 👉 Memory phase: a = undefined 👉 Execution phase: prints undefined 💡 Another example: console.log(b); let b = 20; 👉 Memory phase: b exists but is not initialized 👉 Execution phase: ❌ ReferenceError (because of Temporal Dead Zone) 💡 Functions: sayHi(); function sayHi() { console.log("Hi"); } 👉 Works because functions are fully stored in memory before execution 🎯 So what is Hoisting REALLY? It’s NOT “moving code to the top” ❌ It’s the result of how JavaScript allocates memory inside the Execution Context before execution begins ✅ 💼 Interview Insight: Most people say: 👉 “JS moves variables to top” ❌ Better answer: 👉 “Hoisting is a JavaScript behavior that occurs during the creation phase of the execution context, where memory is allocated for variables and functions before code execution. Variables declared with var are initialized as undefined, while let and const remain uninitialized in the Temporal Dead Zone, and function declarations are stored with their full definition.” #JavaScript #FrontendDeveloper #WebDevelopment #CodingJourney
Sagar raghav’s Post
More Relevant Posts
-
After understanding how JavaScript runs inside the engine (V8, JIT, etc.), today I moved one layer deeper into how JavaScript actually executes code internally. 🔹 Execution Context (EC) JavaScript runs code inside something called an Execution Context, which is basically the environment where code is evaluated and executed. There are two main types: 1. Global Execution Context (GEC) → created once when the program starts 2. Function Execution Context (FEC) → created every time a function is called Each execution context goes through two phases: 1. Creation Phase (Memory Setup) - Variables (var) are initialised as undefined - let/const are in the Temporal Dead Zone - Functions are fully stored in memory - Scope chain is determined 2. Execution Phase - Code runs line by line - Variables get actual values - Functions are executed 🔹 Call Stack (Execution Stack) JavaScript uses a call stack (LIFO) to manage execution: - When a function is called → pushed to stack - When it finishes → popped from stack - This helps track exactly what is running at any moment 🔹 Hoisting During the creation phase: - var → hoisted as undefined - let/const → hoisted but not initialised (TDZ) - Functions → fully hoisted 🔹 Lexical Scope Scope is determined by where code is written, not where it is called. This is why inner functions can access outer variables. 🔹 Closures Closures allow a function to remember variables from its outer scope, even after the outer function has finished execution. This is a powerful concept used in: - Data privacy - State management - Real-world application logic 💡 Big realisation from today: Understanding execution context and the call stack makes JavaScript feel much less “magical” and much more predictable. Instead of guessing what the code will do, I can now trace exactly how it runs step by step. On to Day 3 tomorrow 🔥 #javascript #webdevelopment #programming #softwareengineering #learning #developers
To view or add a comment, sign in
-
-
🚀 JavaScript Hoisting — what it actually means (with a simple mental model) Most people say: “Variables and functions are moved to the top". Even the educators on youtube (some of them) are teaching that and even I remember answering that in my first interview call. That’s not wrong… but it’s also not the full picture. Then Priya what’s really happening? JavaScript doesn’t “move” your code. Instead, during execution, it runs in two phases: 1️⃣ Creation Phase Memory is allocated Variables → initialised as undefined Functions → fully stored in memory 2️⃣ Execution Phase Code runs line by line Values are assigned 🎨 Think of it like this: Before running your code, JavaScript prepares a “memory box” 📦 Creation Phase: a → undefined sayHi → function() { ... } Execution Phase: console.log(a) → undefined a = 10 🔍 Example 1 (var) console.log(a); // undefined var a = 10; 👉 Why? Because JS already did: var a = undefined; ⚡ Example 2 (function) sayHi(); // Works! function sayHi() { console.log("Hello"); } 👉 Functions are fully hoisted with their definition. 🚫 Example 3 (let / const) console.log(a); // ❌ ReferenceError let a = 10; 👉 They are hoisted too… But stuck in the Temporal Dead Zone (TDZ) until initialised. 🧩 Simple rule to remember: var → hoisted + undefined function → hoisted completely let/const → hoisted but unusable before declaration 💬 Ever seen undefined and wondered why? 👉 That’s hoisting working behind the scenes. #javascript #webdevelopment #frontend #reactjs #programming #100DaysOfCode
To view or add a comment, sign in
-
-
I’ve started learning scope in JavaScript, but before diving into it, I took an interesting detour into a very important question: Is JavaScript compiled or interpreted? Before getting into scope properly, I learned that JavaScript does not behave like a simple line-by-line interpreter. A good example is this: ```js console.log("Hello"); function foo() { console....log("world"); } console.log("hello world"); ``` If JavaScript was executed in a purely naive line-by-line way, we might expect "Hello" to be logged before the error appears. But that does not happen. The script fails before execution starts because the JavaScript engine first goes through an initial preparation phase. That phase includes things like: 1. parsing the code 2. checking whether the syntax is valid 3. building an internal representation 4. preparing the code for execution So a better mental model is: Source code -> Parse / syntax check -> Internal representation / compilation steps -> Execution This helped me understand that calling JS simply “interpreted” is not the full picture. Modern JavaScript engines like V8 are much more advanced. They can parse code, create internal representations, interpret some code, compile parts into bytecode or internal instructions, and even JIT-compile frequently used parts for better performance. So JavaScript is commonly called an interpreted language, but in modern engines, the reality is more nuanced. This also connects nicely with scope. Scope is about the visibility of variables and functions in code, but before JavaScript can execute code, the engine first needs to understand the structure of that code. That means scope is not just a runtime topic. It is closely connected to how the engine reads, parses, and prepares the program. My main takeaway: JavaScript is not random, and it is not just “reading one line at a time”. There is a preparation phase before execution, and understanding that makes topics like scope, hoisting, and errors much easier to reason about. #JavaScript #TypeScript #WebDevelopment #SoftwareEngineering #V8 #LearningInPublic
To view or add a comment, sign in
-
-
🚀 **Day 4 – Scope Chain & Lexical Environment in JavaScript** In Day 3, we learned about Execution Context… But now the real question is: 👉 **How does JavaScript find variables when executing code?** 🤔 Let’s understand 👇 --- 💡 **What is Scope?** Scope defines **where a variable can be accessed** 👉 Simple: Scope = where is variable available ? --- 💡 **What is Scope Chain?** When JavaScript tries to access a variable: 👉 It searches in this order: * Current scope * Parent scope * Global scope 👉 This is called **Scope Chain** --- 💡 **Example:** ```js let name = "Aman"; function outer() { let city = "Indore"; function inner() { console.log(name); console.log(city); } inner(); } outer(); ``` --- 💡 **Behind the scenes:** When `inner()` runs: * looks for `name` → not in inner * goes to parent → not found * goes to global → found * looks for `city` → found in outer 👉 JavaScript climbs the **scope chain** --- 💡 **What is Lexical Environment?** 👉 It means: Scope is decided by where code is written, not where it is called --- ⚡ **Key Insight** JavaScript uses: * Scope * Scope Chain * Lexical Environment 👉 to resolve variables --- 💡 **Why this matters?** Because this is the base of: * Closures * Variable access * Debugging scope issues --- 👨💻 Continuing my JavaScript fundamentals series 👉 Next: **Hoisting (most misunderstood concept)** 👀 #JavaScript #WebDevelopment #FrontendDevelopment #Coding #SoftwareEngineer #Tech
To view or add a comment, sign in
-
-
Stop writing JavaScript like it’s still 2015. 🛑 The language has evolved significantly, but many developers are still stuck using clunky, outdated patterns that make code harder to read and maintain. If you want to write cleaner, more professional JS today, start doing these 3 things: **1. Embrace Optional Chaining (`?.`)** Stop nesting `if` statements or using long logical `&&` chains to check if a property exists. Use `user?.profile?.name` instead. It’s cleaner, safer, and prevents those dreaded "cannot read property of undefined" errors. **2. Master the Power of Destructuring** Don't repeat yourself. Instead of calling `props.user.name` and `props.user.email` five times, extract them upfront: `const { name, email } = user;`. It makes your code more readable and your intent much clearer. **3. Use Template Literals for Strings** Stop fighting with single quotes and `+` signs. Use backticks (`` ` ``) to inject variables directly into your strings. It handles multi-line strings effortlessly and makes your code look significantly more modern. JavaScript moves fast—make sure your coding habits are moving with it. What’s one JS feature you can’t live without? Let’s chat in the comments! 👇 #JavaScript #WebDevelopment #CodingTips #SoftwareEngineering #Frontend #Programming
To view or add a comment, sign in
-
🚀 Day 10 of My JavaScript Journey ✨Today I explored how JavaScript actually works behind the scenes — and honestly, it changed the way I look at code completely 🤯 Here’s what I learned 👇 🧠 How JavaScript Code RunsJavaScript doesn’t just execute line by line — it first creates an Execution Context which manages everything. ⚙️ Execution Context Phases1️⃣ Memory Allocation Phase Variables get stored with undefined Functions are stored completely 2️⃣ Execution Phase Code runs line by line Values get assigned and functions execute 📦 Call Stack & Execution Flow JavaScript uses a Call Stack to manage function calls Each function creates its own execution context Stack follows LIFO (Last In, First Out) 💾 Stack vs Heap Memory Stack → Stores primitive values (fast ⚡) Heap → Stores objects (reference-based 🧩) 🤖 Interpreter BehaviorJavaScript reads and executes code step by step using an interpreter — not compiled like some other languages. ❓ Why undefined Appears?Because during memory phase, variables are declared but not initialized yet. ⬆️ Hoisting Explained var is hoisted with undefined Functions are fully hoisted let & const are hoisted but stay in Temporal Dead Zone (TDZ) ❌ 🚫 Temporal Dead Zone (TDZ)You can’t access let & const variables before initialization — it throws an error. ⚠️ Function Expressions vs Hoisting Function declarations → hoisted ✅ Function expressions → behave like variables ❌ 💡 Key TakeawayUnderstanding execution context, memory, and hoisting makes debugging WAY easier and helps write cleaner code 🔥 📌 Slowly moving from writing code → to understanding how it actually works inside #JavaScript #WebDevelopment #MERNStack #CodingJourney #LearnToCode #FrontendDevelopment #DeveloperLife
To view or add a comment, sign in
-
-
🚀 Day 5 — Understanding JavaScript Hoisting & Execution Context Missed sharing yesterday’s update, so posting it today 👇 Continuing my journey of strengthening core JavaScript fundamentals, I explored one of the most important (and commonly asked) concepts in interviews — how JavaScript actually runs behind the scenes. 🔹 Covered topics: - JavaScript Hoisting: • Variables and functions can be used before declaration • Only declarations are hoisted, not initializations • Difference in behavior: var vs let vs const - Temporal Dead Zone (TDZ): • Why let & const throw errors before initialization • Understanding “Cannot access before initialization” - Execution Context (🔥 very important): • How JavaScript executes code internally • Two phases: - Memory Creation Phase - Execution Phase - Memory Creation Phase: • Variables stored as undefined • Functions stored completely - Execution Phase: • Code runs line by line • Values get assigned and functions executed - Function Hoisting: • Function declarations are fully hoisted • Function expressions behave differently - Call Stack: • How JavaScript manages function execution (LIFO) 💡 Key Learning: JavaScript is not executing code line-by-line directly — it first scans and prepares memory, then executes. 👉 Concepts like: - Why var gives undefined but let/const throw error - How execution context is created - How functions are stored and executed - What happens internally before a single line runs These are core interview concepts that define how deeply you understand JavaScript. This phase is helping me move from just writing code → to understanding how JavaScript engine actually works internally ⚡ 📌 Day 5 of consistent preparation — building strong fundamentals step by step 🔥 #JavaScript #WebDevelopment #FullStackDeveloper #CodingJourney #MERNStack #InterviewPreparation #Frontend #Backend #LearnInPublic #Developers #LinkedIn #Consistency #Connections
To view or add a comment, sign in
-
🧠 𝗪𝗿𝗶𝘁𝗶𝗻𝗴 𝗰𝗹𝗲𝗮𝗻𝗲𝗿, 𝘀𝗺𝗮𝗿𝘁𝗲𝗿 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝘄𝗶𝘁𝗵 𝗗𝗲𝘀𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗶𝗻𝗴 Destructuring is one of those features in JavaScript that can significantly improve code readability and enhances Developers Experience—yet it’s often underutilized or misunderstood. So I decided to break it down in a structured way. New Blog Published: “Mastering Destructuring in JavaScript” https://lnkd.in/gHAWq_sP 🔍 What’s covered in the blog: 🔹 Array & object destructuring fundamentals 🔹 Nested destructuring patterns 🔹 Default values cases 🔹 Practical use cases for writing cleaner, maintainable code Hitesh Choudhary Piyush Garg Akash Kadlag Suraj Kumar Jha Chai Aur Code Nikhil Rathore Jay Kadlag DEV Community #JavaScript #WebDevelopment #TechnicalWriting #CleanCode #LearningInPublic #Chaicode #Cohort
To view or add a comment, sign in
-
❓ Quick question: Everything works fine… until you move your variable inside a function or block 💥 Why does JavaScript behave like this? 🤔 👉 What’s actually going on here? 🚀 Let’s decode one of the most confusing JavaScript concepts: Scope (Global, Function, Block) 🌍 1. Global Scope (var, let, const) If a variable is declared outside everything → it becomes globally accessible ✔ Works everywhere: • inside { } • inside if • inside loops • inside functions 💡 That’s why this runs smoothly everywhere. 🧠 2. Function Scope Variables declared inside a function are locked 🔒 inside it. 👉 Outside = ❌ Not accessible 👉 Inside = ✅ Works perfectly 💡 Key Insight: Function creates its own private world 📦 3. Block Scope (let & const) let and const are block scoped That means: 👉 Only accessible inside { } Outside the block → 💥 ReferenceError ⚠️ But here’s the twist… var is NOT block scoped ❗ 👉 It ignores { } blocks 👉 Gets hoisted to function/global scope So: Inside block → defined Outside block → still accessible 😲 🔥 Why this matters (real dev insight) Understanding scope helps you: - Avoid accidental bugs 🐛 - Write predictable code 🧠 - Prevent variable leaks ⚠️ - Debug faster 🚀 💡 Final Thought: Most beginners think: 👉 “Scope is simple” But in real-world apps: 👉 Scope mistakes = silent bugs + messy code 📌 Follow along — I’ll keep breaking down JavaScript concepts in a simple way. #JavaScript #FrontendDevelopment #WebDevelopment #CodingTips #LearnJavaScript #Scope #100DaysOfCode #BuildInPublic
To view or add a comment, sign in
-
-
𝗧𝗵𝗲 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗘𝗻𝗴𝗶𝗻𝗲: 𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝗖𝗮𝗹𝗹 𝗦𝘁𝗮𝗰𝗸, 𝗘𝘅𝗲𝗰𝘂𝘁𝗶𝗼𝗻 𝗖𝗼𝗻𝘁𝗲𝘅𝘁, 𝗮𝗻𝗱 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴 You write JavaScript code every day. But do you know what happens when your code runs? You call functions, declare variables, and sometimes see undefined where you don't expect it. The answer lies in three core JavaScript mechanisms: - the call stack - the execution context - hoisting Understanding these internals helps you fix weird bugs and improve your code quality. The call stack tracks where your code is running. It's like a stack of plates - you can only add or remove from the top. When a function is called, a new frame is added to the stack. When the function returns, that frame is removed. The execution context is how your code runs. It has three parts: - variable environment - lexical environment - this binding Every execution context goes through two phases: creation and execution. During creation, the engine sets up the variable object, scope chain, and this binding. It also hoists declarations - registers them in memory before executing any code. Hoisting is often misunderstood. It's not that JavaScript moves declarations to the top of the file. Instead, the engine scans for declarations and registers them in memory before executing any code. Function declarations are fully hoisted, while var declarations are hoisted but their assignments are not. Let and const declarations are also hoisted, but they're not initialized until their declaration is reached. Understanding the call stack, execution context, and hoisting helps you debug faster, improve performance, and explain complex concepts with confidence. It's not just theory - it has a direct impact on your daily work as a developer. Source: https://lnkd.in/gbPtAu5N
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