Monday, January 13, 2014

JavaScript Best Practices : Variable scoping and hoisting

You may also like to see:


Hoist means in dictionary is "to raise(going up) by means of ropes or pulleys".


In this article we will see hoisting effect of variable in JavaScript. What would be its effect and how to escape these situations?


Lets start with a example code:


var x = 1;
function myFunction() {    
   if (!x) {
     var x = 10;
   }
   alert(x);
}
myFunction();

If you know about JavaScript closures, the function here myFunction have the access to variable x defined outside of the function and in JavaScript 1 = true so condition if(!true) will fail here and alert of value 1 will be prompted at end.

If you are thinking as above the you might be surprised knowing that it is not true.

See here jsFiddle Demo

if you run this code it will give you alert of 10.

Why it is behaving like this?

It is because of Hoisting in JavaScript. Hoisting move the declaration part to the top of scope automatically but not the initialization part.



so above given example code actually treated as:

var x; //declaring hoisted part
x = 1; //initialization not hoisting
function myFunction() {    
  var x;  // hoisted and overwrite outerscope x with undefined  
  if (!x) {
    x = 10;  //not hoisted
  }
  alert(x);
}
myFunction();

That is the reason when myFunction was called it actually overwrite(mask) the parent scope variable and at condition statement it value was undefined due to NOT operator it gets true now value initialized with value 10.

Hoisting also occurs with function, it hoist completely with its body part that is the reason in JavaScript calling function before its declaration.

myFunction();// it will call function without error

function myFunction() {    
   console.log('function get called');
}

above code throws no error (jsFiddle Demo) as it is interpreted as:

function myFunction() {    
   console.log('function get called');
}

myFunction();


How to use this knowledge?


As now you know how confusing variable hoisting can be.In large block of code it is really difficult to understand the scope and hoisting effect which may cause unexpected results. So to avoid this situation always use single var pattern according which define all variables with a single var at the top of scope. Benefits of this technique is that you can find all variable at single place, helps in variable name conflicts and hoisting effect.


You may also like to see:

No comments:

Post a Comment

Life insurance policy, bank loans, software, microsoft, facebook,mortgage,policy,