Skip to main content

Hoisting

This is a JavaScript concept. The compiler moves variable and function declarations up. This is exactly why JS doesn't throw errors when you use 'var' variables before you declare them.

Meaning of the word hoisting

This is just like hoisting a flag up a pole. Here, the variables are pulled up in their scopes.

Hoisting depends on scope of the variable

During hoisting, each variable moves to the highest point its scope allows.

  • var - these are hoisted to the function or the global scope, whichever is the parent. var has no real block scope, even though you can declare it inside a block.
  • let - hoisted within its own scope level.
  • const - hoisted within its own scope level.

Actual hoisting only for var

True hoisting happens only for the var keyword. For the rest, the lexical environments are just created as is.

This is also because var existed from day one of JavaScript. const and let came later.

Hoisting example
function example() {
var a = 1; // Function-scoped
let b = 2; // Block-scoped to function body
{
var c = 3; // Function-scoped (ignores block). Will be moved to top of the function.
let d = 4; // Block-scoped to inner block
console.log(a, b, c, d); // 1, 2, 3, 4
}
console.log(a, b, c); // 1, 2, 3
console.log(d); // ReferenceError: d is not defined. Error during execution.
}

example();

Default value assignment

Only var gets both a hoist and a default value. It moves to the top of its scope. And it's set to 'undefined'.

let and const are hoisted but get no value, not even undefined. Using one before its assignment throws an error at runtime.

Hoisting Process
Lexical Environment and Hoisting

Hoisting is just the creation of the lexical environment. The compiler pulls each variable up to the lexical environment map it belongs to.

Block Scope

In JavaScript, block scope is any code inside curly brackets. But not functions.

Block scope examples

if, for and while loops, closures, etc.

Functions

All functions are also hoisted and added to the corresponding lexical environment.

Not for functions assigned to variables

If you assign a function to a 'const' variable, hoisting follows the const rules. You can't call the function until the variable points to the function definition.