Open In App

How Hoisting works in JavaScript ?

Last Updated : 30 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, hoisting is a mechanism where variable and function declarations are moved to the top of their containing scope during the compilation phase. This means that you can use a variable or call a function before it is declared in your code.

Example 1: Here, Even though the console.log(x) appears before the variable x is assigned a value, it doesn’t result in an error. This is because, during hoisting, the variable declaration is moved to the top, but the assignment remains in its original position.

Javascript




console.log(x); // Outputs: undefined
var x = 5;
console.log(x); // Outputs: 5


Output

undefined
5

Example 2: Here, the function sayHello is called before its declaration in the code. Hoisting moves the entire function declaration to the top, allowing the call to work without errors.

Javascript




sayHello(); // Outputs: "Hello, world!"
function sayHello() {
  console.log("Hello, world!");
}


Output

Hello, world!

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads