How to understand hoisting in JavaScript

· Category: JavaScript

Short answer

Hoisting is JavaScript's behavior of moving declarations to the top of their scope before execution, but only var and function declarations are initialized with undefined; let and const enter a temporal dead zone.

Steps

  1. var declarations are hoisted and initialized as undefined: javascript console.log(a); // undefined var a = 5;
  2. let and const are hoisted but not initialized: javascript console.log(b); // ReferenceError let b = 5;
  3. Function declarations are fully hoisted: javascript sayHi(); // works function sayHi() { console.log('Hi'); }
  4. Function expressions are not hoisted: javascript sayBye(); // TypeError var sayBye = function() { console.log('Bye'); };

Tips

  • Declare variables at the top of their scope to avoid surprises.
  • Prefer let and const because the temporal dead zone catches errors early.

Common issues

  • Repeating var inside loops with closures captures the same hoisted variable.
  • Calling a function expression before its assignment throws an error.