DeltaWeb DeltaWeb - 1 year ago 63
Javascript Question

Why save the array length to a variable before using for(;i<len;)?

I am learning JavaScript and I see in some books/tutorial this:

myvariable = myArray.length;
for(i = 0; i < myVariable; i++){

What's the difference if I write it like this (I mean if I don't create a variable that holds the length of my array and I use
Directly in the

for(i = 0; i < myArray.length; i++)

Which one is better?

P.S: sorry for my bad English it's not my native language.

Thank you.

Answer Source

There is no functional difference with the given code.

There is a slight performance difference (negligible in most cases) in how you declare the variables that are in the for statement.

When doing this:

for(var i = 0; i < someArray.length; i++)

var i and someArray.length are evaluated every iteration. So the total time, d, it take the loop to occur is the time, t, it takes to evaluate a variable, multiplied by the number of iterations, i, of your loop:

d = t*i

Thus, as stated early, this difference will be negligible in most cases. It takes less code to write it the first way, but doing it this way will lower d:

var i = 0,
    len = someArray.length;

for( ; i<len; i++)

However, sometimes evaluating the length of someArray every iteration is necessary due to possible changes in the length of someArray (for example, when removing elements from someArray):

for(var i = 0; i<someArray.length; i++) {
    someArray.splice(someArray.length - 1, 1);

This will remove the last element of someArray, and if you don't recompute the length of someArray for every iteration of the loop, some browsers will throw an error.

To see some examples of how you can write the same loop in many different ways (as well as see the performance differences), see this jsperf (a JavaScript performance test).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download