Saturday, March 14, 2020

JavaScript Hoisting

JavaScript Hoisting

Hoisting is JavaScript's default behavior of placing declarations at the top. Actually, when JavaScript code compiled, all declarations using var are hoisted at the top of their functional scope (if declared inside a function) or local scope or to the top of their global scope (if declared globally) regardless of where the actual declaration has been made. (Here placing does not means putting them physically on the top but placing them in the memory first at the compilation).

Functions declarations are also hoisted in JavaScript, but functions declarations move to the topmost places. Functions declarations are placed above all of the variable and function declarations.

In JavaScript, a variable can be declared after it has been used it means a variable can be used before it has been declared.

  x = 5;
 document.getElementById("demo").innerHTML=x;
 var x;

is equivalent to,

var x;
x = 5;
 document.getElementById("demo").innerHTML=x;

Initializations

The variable initializations are not hoisted, only declarations are hoisted.

JavaScript Hoisting
JavaScript Hoisting


<html>
  <head>
<script>
 name1='Johny';
 name2='Johny';
 document.getElementById("demo").innerHTML=name1+name2;
 var name1;
 var name2;
</script>
  </head>
  <body>
    <button onclick="testPrompt()">Click me</button>
    <div id='demo'></div>
  </body>
</html>

will result

JohnyJohny

but the following code,

<html>
  <head>
<script>
 name1='Johny';
 document.getElementById("demo").innerHTML=name1+name2;
name2='Johny';
 var name1;
 var name2;
</script>
  </head>
  <body>
    <button onclick="testPrompt()">Click me</button>
    <div id='demo'></div>
  </body>
</html>

will result
Johnyundefined

The variable name1 and name 2 are hoisted at the top, but not their initialization, so we are getting the name2 value "undefined". However, name2 is initialized, but it is used before its initialization. Hoisting is generally unknown to the programmers or they overlook hoisting, these induct bugs and errors in the code. It is always best practice to declare variables first and use them later.

let and const Hoisting

The "let" and "const" variables are not hoisted.

Function Hoisting

Functions are hoisted like variables and function declarations are kept at the topmost place during the compilation. The following code,

<script>
f1();
f2();
function f1()
 {
   document.write('Function F1');
 }
function f2()
 {
  document.write('Function F2');
 }
</script>
  

will result

Function F1Function F2