Skip to content

Hoisting in JavaScript: Namaste JavaScript 🔥 Magic Behind Scopes

What is Hoisting in JavaScript? 🪄

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope before code execution. But the real magic lies in how the execution context is created in two phases.

The Key Observation

console.log(getName); // namaste JavaScript
console.log(x);       // undefined

var x = 7;
function getName() {
  console.log("namaste JavaScript");
}
  • ✅ getName(), prints the function, even before it's declared
  • ❌ x, prints undefined, not the value 7
  • ❌ Remove var x = 7 entirely → you get ReferenceError: x is not defined

Difference: undefined means the variable exists in memory but has no value yet. not defined means it doesn't exist at all. To dive deeper into this concept, check out Understanding Variable Scope: Local vs Global Variables in Programming.

How Hoisting Works, The Execution Context 🔍

JavaScript creates an execution context in two phases:

Phase 1: Memory Creation Phase

  • Scans entire code
  • Allocates memory for all variables and function declarations
  • Variables get the placeholder value undefined
  • Function declarations get the entire function code stored

Phase 2: Code Execution Phase

  • Executes line by line
  • Assigns actual values to variables
  • Invokes functions

Debugger Demo

  1. Put a debugger on line 1 before any code runs
  2. Inspect the global scope, you'll already see:
    • x: undefined (memory reserved)
    • getName: f getName() (whole function stored)
  3. This is why you can call getName() before its declaration!

Function Declarations vs Function Expressions 🚨

| Type | Syntax | Hoisting Behavior | |------|--------|------------------| | Function Declaration | function getName() {} | ✅ Whole function is hoisted | | Function Expression (named) | const getName = function() {} | ❌ Treated as variable => undefined | | Arrow Function | const getName = () => {} | ❌ Treated as variable => undefined |

Try this:

console.log(getName); // undefined (because it's an arrow function)
getName();            // TypeError: getName is not a function
var getName = () => console.log("hello");

For a more comprehensive understanding of JavaScript fundamentals, see JavaScript Complete Beginner to Advanced: Need, Origin & Node.js Setup.

Call Stack in Action 🧠

When you invoke a function inside the global code:

  1. A new execution context is created for that function
  2. It is pushed onto the call stack
  3. Once the function finishes, it is popped off
  4. Control returns to the global execution context

Debugger Demonstration

  1. Set breakpoint at line 1
  2. Call stack shows anonymous (global EC)
  3. Step into getName() invocation
  4. A new execution context appears on top: getName
  5. Step out of the function → the getName context disappears
  6. Full execution ends → call stack is empty

Key Takeaways 🎯

  • Hoisting does not physically move code to the top, it's about memory allocation during the creation phase
  • var variables are hoisted with undefined
  • let and const are hoisted but not initialized (Temporal Dead Zone)
  • Function declarations are fully hoisted (code included)
  • Function expressions and arrow functions are hoisted as undefined (like variables)

Interview Answer: "Hoisting happens because JavaScript allocates memory to all variables and function declarations during the memory creation phase of the execution context, before any line of code is executed."

If you're preparing for interviews, be sure to practice with Top 30 JavaScript Interview Questions with Expert Answers and understand unique topics like Currying in JavaScript Explained: Practical Example & Interview Guide.

Keep this summary

Save it to LunaNotes and it becomes a real note in your library — editable, searchable, and ready to turn into flashcards or a diagram. Free to start.

Save to LunaNotes

Or summarise for another video.

32K+ people have turned 65K+ videos into notes

“Very useful tool. I'm using it for the last couple weeks and I'm loving it so far. Makes learning on YouTube a great experience.”
Bhai Chrome Web Store review

This summary and transcript were automatically generated using AI with the Free YouTube transcript summary tool by LunaNotes.

Related summaries

JavaScript Complete Beginner to Advanced: Need, Origin & Node.js Setup

JavaScript Complete Beginner to Advanced: Need, Origin & Node.js Setup

This video kicks off a comprehensive JavaScript series, explaining why JavaScript was created in 1995 despite existing languages like C++ and Java. It covers the need for a secure, lightweight, easy-to-learn language for web interactivity and provides a first-principles thinking approach to understand the JavaScript engine, V8, and how to set up Node.js on your system.

Understanding Variable Scope: Local vs Global Variables in Programming

Understanding Variable Scope: Local vs Global Variables in Programming

Explore the concept of variable scope in programming, focusing on the differences between local and global variables. Learn how variable lifetime and visibility affect program behaviour with clear examples and key principles.

Top 30 JavaScript Interview Questions with Expert Answers

Top 30 JavaScript Interview Questions with Expert Answers

Master JavaScript interviews with this comprehensive guide featuring 30 commonly asked questions ranging from basics to advanced concepts. Gain insights on topics like hoisting, closures, promises, async/await, event delegation, and more, supported by clear examples and best practices for both beginners and experienced developers.

JavaScript 101: Everything Beginners Need to Know in One Video

JavaScript 101: Everything Beginners Need to Know in One Video

JavaScript is both a wonderful and horrible language to learn. This video covers 101 essential concepts—from variables and functions to the event loop, promises, and modules—so you can build websites, apps, servers, and more by the end.

.NET Full-Stack Interview: C#, SQL, Web API & React Concepts Explained

.NET Full-Stack Interview: C#, SQL, Web API & React Concepts Explained

In this mock interview, a full-stack developer with 3.5 years of experience is quizzed on key .NET, SQL, and React concepts. Topics covered range from C# fundamentals like IEnumerable vs IQueryable and async/await, to SQL indexing and normalization, as well as Web API middleware and React hooks.

Found this summary useful?

Take it with you. One click puts it in your own LunaNotes library.

Save to LunaNotes

Start taking better notes today with LunaNotes