learn deep. ship safe.Practice testsFollow ByteMunSubscribe

Concept

Hoisting

How JavaScript registers declarations before running code, and why let and const sit in a temporal dead zone.

Hoisting explained

Hoisting is JavaScript registering declarations before it runs the code in a scope, so some names exist before the line that declares them. Function declarations are fully available from the start of their scope; var variables exist but hold undefined; let, const and class are registered too, but reading them before their declaration throws a ReferenceError. That gap is called the temporal dead zone.

How hoisting works

Before running a function or script, the engine scans it and creates a binding for each declaration. What differs is whether that binding is initialised yet.

sayHi();                 // works: function declarations are hoisted whole
console.log(count);      // undefined: var is hoisted, its value is not
// console.log(total);   // ReferenceError: temporal dead zone
var count = 1;
let total = 2;

function sayHi() { console.log("hi"); }

// greet();              // TypeError: greet is undefined (only the var is hoisted)
var greet = function () {};

What is hoisted, and how

  • Function declarations: name and body. You can call them earlier in the scope.
  • var: the name, initialised to undefined.
  • let, const, class: the name, uninitialised until the declaration runs.
  • Function expressions and arrow functions: only the variable they are assigned to, following that variable's rules.

Common mistakes

  • Calling a function stored in a var or const before the assignment line.
  • Relying on hoisting for readability. Declaring things before you use them is clearer, even where hoisting would allow otherwise.
  • Thinking let is not hoisted. It is, which is why a same-named outer variable cannot be read inside the dead zone either.

What interviewers ask about hoisting

  • "What does this log?" for a var read before assignment: undefined.
  • "What is the temporal dead zone?" The period between entering a scope and the let/const declaration line, when reading the name throws.
  • "Function declaration or function expression: which can you call first?" Only the declaration.

Connections to other concepts

Practise Hoisting

All topics