Hoisting in JavaScript
What is it and how does it work?
JavaScript has a unique mechanism that can sometimes be confusing, especially for beginners. Imagine writing code where you call a variable before it's declared, and you don't get an error. This isn't magic — it's hoisting.
In this article, we'll discuss what hoisting is, how it works in different cases (var, let, const, function declarations, function expressions), how it relates to the Temporal Dead Zone, and what to watch out for.
Hoisting means that JavaScript mechanically "hoists" some declarations to the top of their scope before code execution.
This means even if you declare a variable or function at the bottom of your code, the JS engine first "sees" them, and only then executes your code.
console.log(name); // undefined
var name = "Ani";
The example above is actually interpreted by JS like this:
var name;
console.log(name); // undefined
name = "Ani";
Notice: only the declaration is hoisted, not the assignment.
console.log(x); // undefined
var x = 10;
console.log(y); // ReferenceError
let y = 10;
console.log(z); // ReferenceError
const z = 20;
TDZ is the period when a variable is hoisted but not yet initialized, and if you try to use it, you'll get a ReferenceError.
var
function exampleVar() {
console.log(a); // undefined
var a = 5;
}
exampleVar();
let
function exampleLet() {
console.log(b); // ReferenceError
let b = 5;
}
exampleLet();
const
function exampleConst() {
console.log(c); // ReferenceError
const c = 5;
}
exampleConst();
Function Declarations – Fully hoisted
greet(); // "Hello!"
function greet() {
console.log("Hello!");
}
JS transforms it like this:
function greet() {
console.log("Hello!");
}
greet(); // "Hello!"
Function Expressions – Not hoisted as functions
sayHi(); // TypeError: sayHi is not a function
var sayHi = function () {
console.log("Hi");
};
What actually happens:
var sayHi;
sayHi(); // TypeError
sayHi = function () {
console.log("Hi");
};
Same goes for Arrow Functions
sayYo(); // TypeError
const sayYo = () => {
console.log("Yo");
};