DEV Community

afrin ashar
afrin ashar

Posted on

Variable Hoisting in JavaScript

Variable hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during the compile phase. This means that you can use variables and functions before you declare them in your code.

Key Points:
Declarations are hoisted, not initializations:

Only the declaration of the variable is hoisted to the top, not the initialization. If you try to use a variable before it is initialized, it will be undefined.
Function declarations are fully hoisted:

Unlike variables, function declarations are hoisted along with their definitions. This means you can call a function before you declare it in your code.
Examples:
Variable Hoisting:


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

In this example, the declaration var x is hoisted to the top, but the initialization x = 5 is not. Hence, the first console.log(x) outputs undefined.

Function Hoisting:

`greet(); // Output: Hello, World!

function greet() {
console.log("Hello, World!");
}`

Here, the function greet is hoisted along with its definition, so it can be called before its declaration.

Let and Const:

Variables declared with let and const are also hoisted but are not initialized. They are in a "temporal dead zone" from the start of the block until the declaration is encountered.

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

Top comments (0)