[Explained] What is Javascript hoisting and why is it asked in every interview?

 

Hoisting explained with Mario jumping towards the pole.

Meaning of hoist

to lift or pull something up, often by using ropes, etc.

Source: Google.

What is hoisting in javascript?

The term "hoist" refers to lift something up. Here in javascript, the process of lifting the variables and function declarations to the top. This means whenever the variables or functions are declared, they will be moved to the top so that they can be accessed anywhere in the program even before the declaration. In a Javascript interview, this is the most commonly asked question.

🚀 Variable hoisting example:

Variables can be used even before the declaration. But values can be accessed after the assignment.

NOTE: let and const will not be hoisted so they cannot be used before the declaration.

if you want to know more about let and const click here.


console.log(a); // undefined

// We can access "a" before the declaration.
// Because while compiling it will be moved to top (i.e hoisting)
// When moving up, it will be declared and assigned to undefined.

var a = 10;

console.log(10); // 10

// at this point value of "a" is 10.

 

🚀 Function hoisting example:

Functions can be accessed before the declaration. This is also an example of hoisting flag.


greet();

function greet() {
    console.log('Hello, there.');
}




🎉 Thanks for reading this article. I am very happy that you spent your time on something good. I hope this article gave you a clear idea about hoisting in javascript. Please comment and share this article with someone who really needs this. Thanks again and stay connected for more interesting posts.

 

Post a Comment

Previous Post Next Post