DEV Community

Cover image for What is Hoisting?
Aishanii
Aishanii

Posted on

1 1

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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay