Last Updated: February 25, 2016
·
1.03K
· mattstyles

Declare a local variable, its quicker and more readable than accessing an array

If you’re currently doing something like this in a for loop:

var i = 0,
    anArray = [ ... ];

for ( i = 0; i < anArray.length; i++ ) {
  perform access with anArray[ i ] multiple times
}

Remember that it’s a little quicker to use a local variable (and it’s more readable if the contents of your for loop spans more than a couple of lines/operations):

var i = 0,
    item = null,
    anArray = [ ... ];

for ( i = 0; i < anArray.length; i++ ) {
  item = anArray[ i ]
  perform access with item multiple times
}

jsperf agrees.

As it turns out, Nikolas Zakas also agrees which is no bad thing.

It’s probably worth noting that it’s usually preferable to optimise at the end of completing a feature/fix but in this case I feel it’s more readable so usually adopt this as a best practise right off the bat.

You can usually make this sort of thing even quicker by ditching the for loop in favour of a while loop (http://jsperf.com/fors-vs-while/58), incidentally it looks like Mozilla still reigns supreme for this sort of thing too!

1 Response
Add your response

Or, the ES5 way :)

userList.forEach(function(user) {
    console.log(user.name);
});
over 1 year ago ·