Hoisting mechanism
Hoisting is a JavaScript mechanism in which variable and function declarations are effectively "raised" to the top of their scope before the code runs.
In simpler terms: JavaScript first scans the entire code, registers the declarations, and then starts executing the commands line by line.
Example with var
console.log(a); // undefined
var a = 10;
console.log(a); // 10Why does it work this way? Because during compilation the engine does this:
var a; // the declaration hoisted
console.log(a); // undefined
a = 10; // assignment
console.log(a); // 10In other words, the declaration (
var a) hoists, but the assignment (= 10) does not.
Example with let and const
console.log(b); // ReferenceError
let b = 20;or
console.log(c); // ReferenceError
const c = 30;Although let and const also hoist, they land in the temporary dead zone (TDZ - Temporal Dead Zone),
the section of code from the start of the scope to the point of actual declaration.
During this time, access to the variable is forbidden.
Example with functions
Function Declaration (hoists completely):
sayHi(); // "Hi!"
function sayHi() {
console.log("Hi!");
}The engine "sees" the entire function declaration before the code runs. That's why you can call it before the line where it's defined.
Function Expression (does NOT hoist completely):
sayHello(); // ReferenceError
const sayHello = function() {
console.log("Hello!");
};Here, only the variable declaration hoists (
const sayHello), but not the function assignment. So access is forbidden until initialization (TDZ).
Let's sum up
| What hoists | When it's accessible | Note |
|---|---|---|
var | Immediately, but with value undefined | Can lead to bugs |
let, const | Only after declaration | Before that: TDZ (ReferenceError) |
function declaration | Always (completely) | Can be called before its definition |
function expression | Like its variable (let, const, var) | Not accessible before initialization |
Analogy
Imagine the interpreter first builds the building's blueprint (declarations), and then starts "moving in" (assignments).
- Function declarations - like rooms that are already ready to use.
var- rooms with a nameplate, but empty.letandconst- rooms that are "closed until opening".
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.