Skip to main content

What is the Hoisting in JavaScript?

Hoisting in JavaScript is a behavior where variable and function declarations are moved to the top of their containing scope during the compilation phase, before the code is executed.

This means that you can use functions and variables before they are declared in the code. However, it's important to understand how hoisting works for different types of declarations (var, let, const, and functions).

Variables Hoisting

var declarations:

Variables declared with var are hoisted to the top of their function or global scope.

However, only the declaration is hoisted, not the initialization. This means the variable exists but is undefined until the assignment is reached in the code.

console.log(x); // undefined (hoisted but not initialized)
var x = 10;
console.log(x); // 10

let and const declarations:

Variables declared with let and const are also hoisted, but they are not initialized. They are placed in a temporal dead zone (TDZ) until the declaration is encountered in the code.

Accessing them before the declaration results in a ReferenceError.

console.log(y); // ReferenceError: Cannot access 'y' before initialization
let y = 20;
console.log(y); // 20

Function Hoisting

Function declarations are hoists, while function expressions are not:

// This is function declaration
function foo() { ... }

// This is function expression
var bar = function () { ... }

Function declarations:

Function declarations are fully hoisted, meaning both the function name and its implementation are moved to the top of the scope.

You can call the function before its declaration in the code.

foo(); // "Hello" (function is hoisted)
function foo() {
console.log("Hello");
}

Function expressions:

Function expressions (e.g., var bar = function() {}) are not hoisted in the same way. Only the variable declaration is hoisted, not the assignment.

bar(); // TypeError: bar is not a function (bar is hoisted but undefined)
var bar = function() {
console.log("World");
};

Order of Hoisting

Function declarations are hoisted above variable declarations.

If a variable and a function have the same name, the function declaration takes precedence.

console.log(typeof myFunc); // "function" (function declaration takes precedence)
var myFunc = 10;
function myFunc() {
console.log("I am a function");
}

Key Takeways

  • var: Hoisted and initialized with undefined.
  • let and const: Hoisted but not initialized (temporal dead zone).
  • Function declarations: Fully hoisted.
  • Function expressions: Only the variable is hoisted, not the function.