Showing posts with label single var pattern. Show all posts
Showing posts with label single var pattern. Show all posts

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:

Saturday, January 11, 2014

JavaScript Best Practices : loop optimization

You may also like to see:

As JavaScript is a client sided programming language, JavaScript should not do any complex or really difficult algorithms which take a lot of time computation.As it may cause to hang the browser or affect your site performance.


There are many things to optimize in a code, In this article I will try to discuss some techniques using we can optimize loops in JavaScript.



A simple loop in JavaScript is:



var fruits = ["apple","banana","orange","mango"];
for(var i = 0; i < fruits.length; i++) {
  // do something with fruits[i]
}

See Performance Demo here

This is simplest loop, we don't need to optimize it but if there are a huge number of items in the array to iterate on or there is complex logic in loop to implement, then we might need to make it faster. Following are some optimizations we can implement on this loop.  

Cache the condition to break

This loop will break when variable i is equals to length of the array, each time array checks this condition it will get the length from object, which is just a overhead. We can get the length of the array and assign it variable and use that variable so we don't need to calculate the length each time. This small trick is really beneficial when iterating over huge items.

var fruits = ["apple","banana","orange","mango"];  
for (var i = 0, max = fruits.length;i < max; i++) {    
   // do something with fruits[i] 
} 

See Performance Demo here

Now this will initialize once then it will use the max variable in each iteration.

(Note: Here initialization of i and max is separated with comma not semi-colan var i = 0, max = fruits.length;  

Single var Pattern

According to single var pattern:
Initializing all variable with single var at common place helps to control the scope of variables and avoiding collisions of variable names, unused variables or preventing logical issues due to uninitialized items. If there are 1000 variables and you initialized it with single var keyword, will save your more than 3000 characters which make your code lesser in size and make it even readable after minifying with some tool.

Using a single var for initialization of all the variable include in iteration can further optimize the performance, with a minor drawback of making copy-paste harder for a loop when refactoring a code.

var i, max, fruits = ["apple","banana","orange","mango"]; 
for (i = 0, max = fruits.length;i < max; i++) {
   // do something with fruits[i]
}

Making simplest increment  

i++ is a bit tricky operator what it actually do:
  • make a temporary copy of variable i
  • increment variable i
  • return the temporary copy for current use
so replacing this with i += 1 or i=i+1 will effect the loop positively.

var i, max, fruits = ["apple","banana","orange","mango"]; 
for (i = 0, max = fruits.length;i < max; i+=1) {
   // do something with fruits[i]
}

See Performance Demo here

Reverse loop

If we iterating over a loop for all the elements in a collection reverse loop starting from a length of collection to zero is faster than above given techniques, it completely depends on the situation whether to use this technique or not. As zero in JavaScript is equal to false so it will automatically break the loop on zero. In this technique condition testing and decrement is occurring in one step which making performance faster.

var i, fruits = ["apple","banana","orange","mango"]; 
for (i = fruits.length; i-=1;) {
   // do something with fruits[i]
}

See Performance Demo here

Making cleaner while-loop

If reverse loop iteration is possible then making it as while loop is more cleaner, it would not make code faster but will surely make it cleaner, readable, easy to understand.

var fruits = ["apple","banana","orange","mango"],i = fruits.length;
while(i-=1) {  //for readability use i--
   // do something with fruits[i]
}


See decrement operator performance difference here.

Summary

It is not necessary that you always get benefits from using these best practices as in small collection all above techniques might produce performance but when you are implementing complex algorithms with a number of collections then you will get the benefits of good code. So making it practice to use best practices always, will make your code and performance better even when you not realize it.


You may also like to see:
Life insurance policy, bank loans, software, microsoft, facebook,mortgage,policy,