Skip to main content

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

javascript
console.log(a); // undefined var a = 10; console.log(a); // 10

Why does it work this way? Because during compilation the engine does this:

javascript
var a; // the declaration hoisted console.log(a); // undefined a = 10; // assignment console.log(a); // 10

In other words, the declaration (var a) hoists, but the assignment (= 10) does not.


Example with let and const

javascript
console.log(b); // ReferenceError let b = 20;

or

javascript
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):

javascript
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):

javascript
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 hoistsWhen it's accessibleNote
varImmediately, but with value undefinedCan lead to bugs
let, constOnly after declarationBefore that: TDZ (ReferenceError)
function declarationAlways (completely)Can be called before its definition
function expressionLike 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.
  • let and const - rooms that are "closed until opening".

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.