Hoisting in JavaScript

Hoisting allows you to use functions and variables in your code even before they’ve been declared. However, the behavior differs based on how the variable or function is declared.

Function Hoisting

Functions declared using function declarations are fully hoisted. This means you can invoke a function before it appears in your code.

sayHello(); // Output: "Hello!"

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

In this case, the function is fully hoisted, so it works even when called before its definition.

Variable Hoisting: var vs let/const

Variables declared using var are hoisted but not initialized. They are assigned undefined during the memory creation phase. On the other hand, variables declared with let and const are also hoisted but remain in the Temporal Dead Zone (TDZ) until their declaration is reached.

console.log(a); // undefined
console.log(b); // ReferenceError: Cannot access 'b' before initialization
console.log(c); // ReferenceError: Cannot access 'c' before initialization

var a = 10;
let b = 20;
const c = 30;
  • var: The variable a is hoisted and initialized to undefined, so no error occurs, but the value is not assigned until later in the code.
  • let and const: Variables b and c are hoisted but remain in the Temporal Dead Zone, causing a ReferenceError if accessed before declaration.

Understanding the Temporal Dead Zone (TDZ)

The Temporal Dead Zone (TDZ) is the period between entering a scope and encountering the declaration of a let or const variable. During this phase, accessing these variables will result in a ReferenceError.

Example with TDZ:

{
  console.log(myVar); // undefined
  console.log(myLet); // ReferenceError
  console.log(myConst); // ReferenceError

  var myVar = "var";
  let myLet = "let";
  const myConst = "const";
}
  • Variables declared with var are available but undefined in the TDZ.
  • Variables declared with let and const are inaccessible until their initialization occurs.