Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their scope before code execution.
This doesn’t mean the code is physically moved, but the JavaScript engine processes declarations first, then executes.
varconsole.log(a); // undefined
var a = 5;The variable a is hoisted, but the assignment (= 5) happens later. Internally, it behaves like this:
var a;
console.log(a); // undefined
a = 5;let and constconsole.log(b); // ReferenceError
let b = 10;let and const are hoisted too, but enter the TDZ (Temporal Dead Zone) — a phase where the variable exists but accessing it throws an error until initialization.
greet(); // "Hello!"
function greet() {
console.log("Hello!");
}Functions declared with function declaration are fully hoisted, including their body.
sayHi(); // TypeError: sayHi is not a function
var sayHi = function() {
console.log("Hi");
};sayHi is declared using var, so it’s hoisted as undefined. The function is not yet assigned at call time.
| Construct Type | Hoisted? | Comment |
|---|---|---|
var | Yes | Declaration is hoisted, but initialization is not |
let / const | Yes (in TDZ) | ReferenceError before initialization |
function declaration | Yes | Fully hoisted with the function body |
function expression | Partially | Variable hoisted as undefined, not the function |
arrow function via const | Yes (in TDZ) | ReferenceError before initialization |
console.log(name);
var name = "Aleksandr Ermolov";sayHello();
function sayHello() {
console.log("Hello");
}sayBye();
var sayBye = function () {
console.log("Bye");
};console.log(age);
let age = 30;greet();
const greet = () => {
console.log("Hi!");
};if (true) {
var test = "yes";
}
console.log(test);var and function declaration are hoisted, let/const too but live in the TDZ.Want more articles on interview preparation?
Follow EasyAdvice, bookmark the site, and level up every day 💪