Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 38

Understanding Hoisting in JavaScript

This lesson is built with resources from youtube.com, fireship.dev and 1 more site.

Hello! Welcome to our next lesson.

In our last session, we visualized how JavaScript uses the Call Stack to manage function calls. We also established that every Execution Context has two distinct phases: a Creation Phase where memory is set up, and an Execution Phase where the code runs line-by-line.

Today, we're going to zoom in on that Creation Phase. This will help us understand a unique JavaScript behavior called hoisting. You might have heard that hoisting is about "moving declarations to the top," but as you'll see, the reality is more nuanced and ties directly into how the JavaScript engine prepares to run your code. This deep-dive is perfect for your goal of understanding why things work the way they do under the hood.

By the end of this lesson, you will be able to describe the concept of hoisting for variables (var, let, const) and function declarations.

The Foundation: Declaration vs. Initialization

Before we can understand hoisting, we must be clear on two separate actions: declaring a variable and initializing it.

  • Declaration: This is when you tell the program that a variable exists, for example: let a;. You've created a label 'a' and reserved a spot in memory for it.
  • Initialization: This is when you give that variable its first value, for example: a = 100;.

Often, we do both on the same line (let a = 100;), but JavaScript treats them as two distinct steps.

Understanding Hoisting in JavaScript | Day 17 | Complete JavaScript Course

To see this distinction clearly, let's watch a quick segment from the video 'Understanding Hoisting in JavaScript' by TAP ACADEMY. This will set the stage for everything that follows.

Watch from 01:03 to 02:05. The instructor does an excellent job of breaking down a single line of code into its separate declaration and initialization parts.


Hoisting with var: The Classic Behavior

Let's look at a classic hoisting puzzle. What do you think this code will output?

console.log(myVar); // What happens here?
var myVar = 10;

Someone new to JavaScript might expect a ReferenceError, because we're using myVar before it's declared. However, the output is undefined. This is hoisting in action.

During the Creation Phase, the JavaScript engine scans the code for variable and function declarations. When it finds var myVar, it allocates memory for it and gives it a default initial value of undefined. Then, during the Execution Phase, the code runs. By the time console.log(myVar) executes, myVar already exists in memory with the value undefined.

The video you just started provides a fantastic visual explanation of this process, using memory diagrams that align with your interest in deep theory.

Understanding Hoisting in JavaScript | Day 17 | Complete JavaScript Course

Let's continue with the TAP ACADEMY video to see exactly how var is hoisted.

Please watch from 03:59 to 14:01. This is a detailed segment, but it's worth it. First, he demonstrates the undefined output (03:59 - 05:30). Then, he walks through a memory diagram (05:30 - 14:01), showing how the declaration is processed in the 'creation phase' (getting the value undefined) before the 'execution phase' even begins. Pay close attention to this visualization.

It's crucial to understand that the code isn't literally being re-written. Rather, declarations are processed before execution, which gives the effect of them being "hoisted" to the top.


Hoisting with let and const: The Temporal Dead Zone

Modern JavaScript introduced let and const, which also get hoisted, but they behave differently and more predictably.

Let's change var to let in our previous example:

console.log(myLet); // What happens now?
let myLet = 10;

If you run this, you get a ReferenceError: Cannot access 'myLet' before initialization. Why the difference?

When the engine hoists a let or const variable during the Creation Phase, it reserves memory for it but does not initialize it. The variable is in an "uninitialized" state. It only gets initialized when the let myLet = 10; line is executed.

Hoisting in JavaScript: Var vs. Let
This image provides a simple visual summary: trying to access a `var` before its declaration line is allowed (you get `undefined`), but doing the same with `let` is not.

The time between the start of the scope and the line where the let/const variable is declared is called the Temporal Dead Zone (TDZ). Any attempt to access the variable within this "zone" will result in a ReferenceError. This is a safety feature that prevents you from accidentally using a variable before it has a meaningful value.

Let's return to our video guide for another excellent visual walkthrough.

Understanding Hoisting in JavaScript | Day 17 | Complete JavaScript Course

The TAP ACADEMY video explains this behavior and the Temporal Dead Zone very clearly.

Now watch from 14:11 to 22:03. let Hoisting (14:11 - 18:27): See the memory diagram for let and note how the variable is left empty/uninitialized, which causes the error. Temporal Dead Zone (18:27 - 20:59): This section gives a formal name to the 'zone' where the error occurs. Summary (20:59 - 22:03): He presents a great summary table comparing var and let hoisting.

This behavior of let and const is a key reason they are preferred over var in modern JavaScript. They lead to cleaner, less error-prone code by enforcing that you declare a variable before you use it.


Hoisting Function Declarations

Hoisting works differently, and perhaps most intuitively, for function declarations.

A Guide to JavaScript Hoisting
As this slide shows, you can call a function before its declaration in the code, and it works perfectly. This is due to function hoisting.

When the JavaScript engine finds a function declaration during the Creation Phase, it doesn't just set aside a name. It allocates memory and stores the entire function body.

This means that by the time the Execution Phase begins, the function is fully defined and ready to be called from anywhere in its scope.

Understanding Hoisting in JavaScript | Day 17 | Complete JavaScript Course

Let's see the final memory diagram from the TAP ACADEMY video to understand how function hoisting works.

Watch from 22:03 to 25:33. The instructor demonstrates how the entire function declaration is 'moved' to the top during the hoisting process, making it available for calls that appear earlier in the code.

Test your understanding!

Consider the following code. What will be logged to the console, and in what order? Think about the hoisting rules for var, let, and function declarations.

console.log(a);
var a = 1;

console.log(b);
let b = 2;

sayHello();
function sayHello() {
  console.log("Hello!");
}
Show answer

The output will be:

  1. undefined
  2. ReferenceError: Cannot access 'b' before initialization

Here's why:

  • var a is hoisted and initialized with undefined. The console.log(a) runs before a is assigned the value 1, so it prints undefined.
  • The code then attempts to log b. Since let b is hoisted but not initialized (it's in the Temporal Dead Zone), this line throws a ReferenceError.
  • The execution stops immediately due to the error, so sayHello() is never called. If the let b lines were removed, sayHello() would have been hoisted and "Hello!" would have been printed successfully.

A Common Pitfall: Function Declarations vs. Function Expressions

It's vital to distinguish between a function declaration and a function expression. They are hoisted differently.

// Function DECLARATION
// Hoisted fully. This works!
sayHi();

function sayHi() {
  console.log("Hi!");
}

// Function EXPRESSION
// This will fail.
sayBye();

var sayBye = function() {
  console.log("Bye!");
};

Why does sayBye() fail? Because sayBye is just a variable declared with var. It is hoisted and assigned the value undefined. When the code tries to execute sayBye(), it is essentially trying to do undefined(), which results in a TypeError: sayBye is not a function.

This distinction is a perfect example of how understanding the underlying rules of variable and function hoisting helps you debug and write correct code.


Conclusion

You've just taken a deep dive into one of JavaScript's most fundamental and often misunderstood concepts. By connecting hoisting to the Creation Phase of the Execution Context, you now have a solid mental model for how the engine prepares your code.

Key Takeaways:

  • Hoisting is JavaScript's behavior of processing declarations before code execution. It happens during the Creation Phase of an Execution Context.
  • var variables are hoisted and initialized with a default value of undefined.
  • let and const variables are hoisted but remain uninitialized. Accessing them before their declaration results in a ReferenceError due to the Temporal Dead Zone (TDZ).
  • Function declarations are hoisted completely—both the name and the full function body are stored in memory before execution, allowing them to be called anywhere in their scope.
  • Function expressions are not hoisted. The variable they are assigned to is hoisted according to its own rules (var, let, or const), which usually leads to errors if called before assignment.
  • Best Practice: To write clear and predictable code, declare your variables at the top of their scope and always use let and const over var.

Next Up:

Now that we understand how variables are scoped and how they come into existence through hoisting, we are ready to tackle one of the most powerful concepts in JavaScript: closures. In the next lesson, we will explore how a function can "remember" and access variables from its parent's scope, even after the parent function has finished executing.