JavaScript ยท Chapter 42 of 55

JavaScript Hoisting

Hoisting is JavaScript's behavior of moving declarations to the top of their scope during compilation, before code actually executes.

Function declarations are fully hoisted (usable before their definition), but `let` and `const` are hoisted into a 'temporal dead zone' where accessing them before declaration throws an error.

Function hoisting

You can call a function declared with `function name(){}` before its line in the code, because the whole function is hoisted.

let/const and the temporal dead zone

Unlike var (hoisted as undefined), let and const exist in a 'temporal dead zone' from the start of the block until their declaration line โ€” accessing them early throws a ReferenceError.

Example 1 (javascript)
console.log(add(2, 3));
function add(a, b) {
  return a + b;
}
Output
5

Function declarations are hoisted, so calling add() before its definition works.

Example 2 (javascript)
console.log(typeof x);
var x = 5;
Output
undefined

var is hoisted with an initial value of undefined, not an error.

Key points

  • Function declarations are fully hoisted and callable early.
  • var declarations are hoisted but initialized as undefined.
  • let/const are hoisted but unusable until declared (temporal dead zone).
  • Function expressions and arrow functions are not hoisted like declarations.
๐Ÿ’ก Note: Relying on hoisting can make code confusing โ€” always declare variables before use for clarity.

๐Ÿ“ Quick Quiz

1. Are function declarations hoisted?

2. What is the value of a hoisted `var` before assignment?

3. Accessing a `let` variable before its declaration causes: