Friday 7 December 2018

What is Variable Hoisting?

In JavaScript, variable declarations are processed before executing any code. This process is called variable hoisting. That means, you can use a variable before its declaration.

HelloWorld.js
function do_something() {
  x = 100;
  console.log("Value of x is : " + x);
  
  var x;
}

do_something();


When you ran HelloWorld.js, you can see below messages in console.
Value of x is : 100

As per variable hoisting, variable declarations are processed before code execution, so HelloWorld.js implicitly understood like below.

function do_something() {
  var x;
  x = 100;
  console.log("Value of x is : " + x);
}

do_something();

One point to remember is, hoisting affects the variable declaration, but not its initialization.

HelloWorld.js
function do_something() {
  
  console.log("Value of x is : " + x);
  
  var x;
  x = 100;
  
  console.log("Value of x is : " + x);
}

do_something();

Output
Value of x is : undefined
Value of x is : 100

As per hoisting, above snippet can be understood like below.

function do_something() {
  var x;
 
  console.log("Value of x is : " + x);
 
  x = 100;
 
  console.log("Value of x is : " + x);
}


do_something();





Previous                                                 Next                                                 Home

No comments:

Post a Comment