DEV Community

Cover image for What is Hoisting?
Aishanii
Aishanii

Posted on

What is Hoisting?

Hoisting is simply access the functions before they are declared.

Let's take up an example:

disp()
console.log(x);

var x=20;
function disp(){
    console.log("30DaysofJS")
}
Enter fullscreen mode Exit fullscreen mode

Calling a function and a variable before declaring them. The output here is, surprisingly,
Image description

In JS, the variables are all initialized as undefined in the first stage of memory allocation, hence even before the execution of code, it gives undefined rather than an error.

For a function, it puts a copy of the whole function in the first stage (in global memory space).

But an arrow function is treated as a variable and given an undefined placeholder.

What about let & const?

console.log(n); 

let n = 26;
Enter fullscreen mode Exit fullscreen mode

The output is as follow, the let and const declarations are given memory but are not given a placeholder hence the error.

Image description

JavaScript only hoists declarations, not initializations! This means that initialization doesn't happen until the associated line of code is executed
๐ŸŒŸ Hoisting by MDN
๐ŸŒŸ Hoisting in JS| Akshay Saini

Top comments (0)