DEV Community

Cover image for Hoisting in JavaScript
Rakshambika
Rakshambika

Posted on

Hoisting in JavaScript

What is Hoisting in JavaScript?

Hoisting is the behavior of moving declarations to the top of their scope before the code is executed.

Hoisting with var:

Variables declared with var are hoisted and initialized with undefined.

Example:

<script>
console.log(name);

var name = "Raksha";

</script>
Enter fullscreen mode Exit fullscreen mode

Output:

undefined
Enter fullscreen mode Exit fullscreen mode

Hoisting with let:

  • Variables declared with let are hoisted but not initialized.
  • They remain in the Temporal Dead Zone (TDZ) until the declaration is reached.

What is Temporal Dead Zone?

  • TDZ (Temporal Dead Zone) is the period between entering a scope and the point where a let or const variable is declared and initialized.
  • During this period, the variable exists in memory, but JavaScript does not allow access to it.

Example:

<script>
console.log(age);

let age = 21;
</script>
Enter fullscreen mode Exit fullscreen mode

Output:

ReferenceError: Cannot access 'age' before initialization.
Enter fullscreen mode Exit fullscreen mode

Hoisting with const:

  • Variables declared with const are hoisted but not initialized.
  • They remain in the Temporal Dead Zone (TDZ) until the declaration is reached.
  • const behaves similarly to let.

Example:

<script>
console.log(PI);

const PI = 3.14;
</script>
Enter fullscreen mode Exit fullscreen mode

Output:

ReferenceError: Cannot access 'age' before initialization.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)