What is hoisting in JavaScript?
- Technology:
- JavaScript
- Topics:
- Functions & Scope
Quick answer
Hoisting is JavaScript moving declarations to the top of their scope during compilation, so functions and var variables can be referenced before the line where they are written.
Detailed explanation
Before running code, the engine processes declarations in each scope. Function declarations are hoisted with their full body, so you can call them before they appear. var variables are hoisted and set to undefined, but their assignment stays where you wrote it.
let, const and class declarations are hoisted too, but not initialised. Accessing them before the declaration throws a ReferenceError (the temporal dead zone). Function expressions assigned to a variable follow the variable's rules, not the function declaration rules.
Example
sayHi(); // "hi" - function declaration is fully hoisted
console.log(x); // undefined - var is hoisted, value is not
console.log(y); // ReferenceError - let is in the temporal dead zone
function sayHi() { console.log("hi"); }
var x = 5;
let y = 10;
notYet(); // TypeError: notYet is not a function
var notYet = function () {};How to explain it in an interview
Hoisting means declarations are registered before the code in a scope runs. Function declarations are available with their body, var variables exist but are undefined until assigned, and let, const and class are in the temporal dead zone until their line runs.
Key points
- Declarations are hoisted, assignments are not
- Function declarations are available before their definition
- let and const exist but cannot be used until declared
Common mistakes
- Describing hoisting as code physically moving to the top. Nothing moves; the engine creates the bindings during the creation phase.
- Expecting a function expression assigned to a var to be callable early. Only the variable is hoisted, as undefined.