Return to the homepage

Optimizing for loop in javascript

We normally don't pay much attention when it comes to writing simple loops and assigning variables.

Here I would like to show two ways of writing a simple code that alerts an array's value.

var arr = new array("red","green","blue");
var len = arr.length;
for(var i=0; i<len; i++) {
	var value = arr[i];
	alert(value);
}

You could write the same script in a more optimized way

var arr = new array("red","green","blue");
for(var i=0,len=arr.length; value=arr[i], i<len; i++) {
	alert(value);
}

Posted by Sunil Lukose on Oct 22, 2008


Sunil Lukose

Share/Save/Bookmark

Posted in News

You can follow any responses to this entry through the RSS 2.0 feed.

You can leave a response, or trackback from your own site.

2 Responses to “Optimizing for loop in javascript”

  1. anonymous - October 23rd, 2008 at 11:38 am

    You don’t say why it’s more optimized and that is much harder to skim. Unless it is significantly faster which you haven’t demonstrated, the amount of time it would take someone to understand and debug it at a simple glance is too much.

  2. anonymous - October 23rd, 2008 at 11:42 am

    Also you fail to mention that reversing loops to use — instead of ++ can double the speed.

    See:
    http://archive.devwebpro.com/devwebpro-39-20030514OptimizingJavaScriptforExecutionSpeed.html

    Listing 10.10

Leave a Reply

Security Code: