Hoisting in JavaScript

What is Hoisting in JavaScript? How to use Hoisting?

  idkblogs.com      July 28, 2021

Shubham Verma

Shubham Verma


Hoisting in JavaScript

What is Hoisting in JavaScript? How to use Hoisting?

Hoisting is one of the default behavior of moving declaration to the top in JavaScript. In this tutorial, we will learn about JavaScript hoisting with the help of examples. The concept of hoisting is very important becase it causes error many time if you haven't use this concept properly.

In JavaScript, Hoisting is a behavior in which a variable or a function can be used before declaration.

Note:
In strict mode "use strict;", JavaScript does not allow variables to be used if they are not declared.

For example,

The above codes will work fine and the output will be undefined, internally this will behave as:

Note:
If we talk about the variables and constants, keyword var is hoisted and let and const does not allow hoisting.


Examples




Hoisting, inside the function:

When we use any variable in the function scope, the variable is hoisted only to the top of the function. Outside the function scope, it will throw an error "Uncaught ReferenceError: X is not defined", For example:

Note:
In JavaScript hoisting, the variable declaration is only accessible to the immediate scope. If you are using let then you can not use hoisting behavior. While using let, the variable must be declared first.


Examples with let and const:

Function Hoisting in JavaScript:

A function can be hoisted in JavaScript, It means a function can be called before declaring it. For example,

Here is an issue with function hoisting:

If you are using an function expression it will throw an error, because only declarations are hoisted.

If you use var in the above codes, then you will get another error "Uncaught TypeError: test is not a function".


Thank you

for taking the time to read this article. If you’re interested in Node.js or JavaScript this link will help you a lot.

If you found this article is helpful, then please share this article's link to your friends to whom this is required, you can share this to your technical social media groups also. You can follow us on our social media page for more updates and latest article updates.
To read more about the technologies, Please subscribe us, You'll get the monthly newsletter having all the published article of the last month.