Intern / FresherJavaScript

What is hoisting in JavaScript?

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.

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.

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 () {};

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