How does variable hoisting differ between var, let, and const?

Umar Farooque Khan
2 min readJun 8, 2023

--

variable hoisting

Variable hoisting behaviour differs between var, let, and const in JavaScript. Here's a breakdown of how each of these declarations is hoisted:

1. var Hoisting:

  • Variables declared with var are hoisted to the top of their scope, known as "hoisting up".
  • During the hoisting phase, the variable declaration is moved to the top of the scope, while the initialization remains in place.
  • The variable is assigned the value undefined by default until its actual assignment is encountered in the code.

Example:

var Hoisting

2. let and const Hoisting:

  • Variables declared with let and const are hoisted as well, but there is a key difference known as the Temporal Dead Zone (TDZ).
  • During the hoisting phase, the variable declaration is moved to the top of the scope, just like with var.
  • However, unlike var, variables declared with let and const remain uninitialized in the TDZ.
  • Attempting to access the variable before its declaration results in a ReferenceError because it is in the TDZ.

Example:

let and const Hoisting

Conclusion:

In summary, var variables are hoisted to the top of their scope and initialized with a value of undefined. On the other hand, let and const variables are hoisted but remain uninitialized within the TDZ, resulting in a ReferenceError if accessed before their declaration. Therefore, it's important to be aware of the hoisting behavior while writing JavaScript code and ensure variables are declared before using them to avoid any unexpected outcomes.

--

--

Umar Farooque Khan
Umar Farooque Khan

Written by Umar Farooque Khan

Experienced software developer with a passion for clean code and problem-solving. Full-stack expertise in web development. Lifelong learner and team player.

No responses yet