What is hoisting in JavaScript?
Hoisting is a mechanism in JavaScript, when the JavaScript interpreter moves all variable and function declarations to the top of the current scope.
It's important to keep in mind that only the javascript hoisting is applicable only for declaration not initialization. It is required to initialize the variables and functions before using their values.
There are 2-kinds of hoisting declaration in javascript.
Variable hoisting.
Function hoisting.
Note : Hoisting is done during the interpreter's first run through the code.
1.) Variable hoisting :
Variable hoisting is a default behaviour in JavaScript where all variable declarations are moved to the top of the current scope (function scope or global scope) that the variable is defined within.
Let’s see an example of variable hoisting :
In this example, we can see in a normal scenario, when x is used before the declaration. In this case, it will give output 10 as excepted.
➤ Example 1 : Variable declaration before hoisting ;
<script> x=10; //Assign 10 to x; document.write(x); var x; //Declare x </script>
Let's take a look at how JavaScript interprets Example 1, how does it look after the hoisting process is finished. Javascript compiler change Example 1 to Example 2.
➤ Example 2 : Variable declaration after hoisting;
<script> var x; //Declare x, (Hoisted) x = 10; //Assign 10 to x document.write(x); </script>
Example 2, Explanation :
In Example 2, we can see JavaScript hoisting behavior var x; is declared before the initialisation(x=10;). In this case, variable declarations are moved to the top.
2.) Function hoisting :
Hoisting only applies to function declarations (not function expressions).
Let’s see an example of function hoisting :
➤ Example :
<script> //Calling function before declaration sayHello(); function sayHello() { document.write("Hello, I am hoisted!"); } </script>
Output :
Hello, I am hoisted!
Comments