How Hoisting works in JavaScript ?
Last Updated :
30 Jan, 2024
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);
var x = 5;
console.log(x);
|
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();
function sayHello() {
console.log( "Hello, world!" );
}
|
Share your thoughts in the comments
Please Login to comment...