DEV Community

Cover image for Hoisting
Chhavi Kohli
Chhavi Kohli

Posted on • Edited on

Hoisting

“Why does my code sometimes work even when I use variables before declaring them?”

What Is Hoisting?

Hoisting in JavaScript is a behavior where declarations of variables, functions, and classes are processed and allocated memory during a compilation phase (Creation Phase) before the code is executed line by line.

This process is not a literal "moving up" of your code, but rather the JavaScript engine's way of creating an "environment record" for the current scope.

console.log(a);
var a = 10;
Enter fullscreen mode Exit fullscreen mode

Output

According to definition from google variable is shifted to top. So output should be 10;

10❌
undefined✅

How?

Only declarations not initialisation

Under the Hood: The Two Phases

Creation Phase (Compilation/Memory Allocation):

  • The engine reads the entire scope of the code (global or function scope).
  • It identifies all function and variable declarations (var, let, const, function).
  • It allocates memory for these declarations in a memory container called the Variable Object.
  • For var declarations, a placeholder value of undefined is assigned.
  • For let and const declarations, they are hoisted but remain uninitialized (will discuss further in blog).
  • For function declarations, the entire function definition is stored in memory, allowing them to be called anywhere within their scope.

TEMPORAL DEAD ZONE - Zone created for the duration between memory allocated and initialisation statement is executed.

Execution Phase:
The engine begins running the code line by line.

  • Because memory has already been allocated, variables and functions are available for use, even if the line where they were "declared" in the source code hasn't been reached yet.
  • When the engine encounters an assignment (=), it updates the value in the allocated memory space.

How let, const hoisting different from var.

Top comments (1)

Collapse
 
dineshrawat profile image
Dinesh Rawat

The distinction between memory allocation and code execution is such a great way to visualize this. Best explanation of Hoisting I've read in a while.