Chapter 05 โ€” Hoisting

๐Ÿ“– Definition

Hoisting is JavaScript's behavior of moving declarations (not initializations) to the top of their containing scope during the compilation phase, before code executes.

๐Ÿ” Explanation

Before any code runs, the JS engine scans the code and registers all declarations:

Declaration Hoisted? Initialized?
var โœ… Yes โœ… to undefined
let / const โœ… Yes โŒ TDZ until line of declaration
function (declaration) โœ… Yes โœ… to the function
function (expression) follows variable rules depends on var/let/const
class โœ… Yes โŒ TDZ

Temporal Dead Zone (TDZ) โ€” the period between entering the scope and the actual let/const/class declaration line. Accessing the variable in that window throws ReferenceError.

๐Ÿ’ป Code Example โ€” var Hoisting

console.log(a); // undefined  (declaration hoisted, value not)
var a = 10;
console.log(a); // 10

// Equivalent to:
// var a;
// console.log(a);
// a = 10;
// console.log(a);

๐Ÿ’ป Code Example โ€” let/const and the TDZ

console.log(b); // โŒ ReferenceError: Cannot access 'b' before initialization
let b = 20;

console.log(c); // โŒ ReferenceError
const c = 30;

๐Ÿ’ป Code Example โ€” Function Declaration vs Expression

// Function DECLARATION โ€” fully hoisted
sayHi();                       // "Hi!"
function sayHi() { console.log("Hi!"); }

// Function EXPRESSION assigned to var โ€” only var is hoisted
sayBye();                      // โŒ TypeError: sayBye is not a function
var sayBye = function () { console.log("Bye!"); };

// Function EXPRESSION assigned to let โ€” TDZ
sayHello();                    // โŒ ReferenceError
let sayHello = function () { console.log("Hello!"); };

๐Ÿ’ป Code Example โ€” Arrow Functions

// Arrow functions are NOT hoisted like declarations
greet();                       // โŒ ReferenceError
const greet = () => console.log("Hello");

๐Ÿ’ป Code Example โ€” Hoisting Order

function test() {
  console.log(x);              // [Function: x]
  var x = 10;
  function x() {}              // function declarations win the initial value
  console.log(x);              // 10
}
test();

๐ŸŒ Real-World Impact

  • Always declare with const/let to avoid var hoisting surprises.
  • Place function declarations near the top of files for readability โ€” hoisting masks bad ordering.
  • Linters (ESLint no-use-before-define) catch most hoisting bugs.

๐ŸŽฏ Likely Interview Questions

  1. What is hoisting?
  2. What is the Temporal Dead Zone?
  3. Are arrow functions hoisted? โ€” No. They follow variable hoisting rules.
  4. What's the difference between function declarations and function expressions in terms of hoisting?
  5. Output prediction:
    var a = 1;
    function foo() {
      console.log(a);
      var a = 2;
    }
    foo(); // undefined โ€” local `a` is hoisted and shadows the outer

โ† Closures | Index | Next: Scope โ†’