Array Iteration

Share

Two quick ways to iterate through an array (from .length to 0).

What’s the point?

  • It’s fast to compare something to zero
  • Less code overall

Why it’s weird…

We’re used to counting from zero to length – not vice-versa

When not to use

The only place I can think of that this wouldn’t be a good idea would be when you need to iterate over the array in ascending key order.

var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
var b = a.length;

// quickly iterate through array
while (b--) {
    console.log(a[b]);
}

// declaring var in same line
for (var c = a.length; c--; ) {
    console.log(a[c]);
}

// of course THIS is best
a.forEach(i => console.log(i));
Share

Leave a Reply

Your email address will not be published. Required fields are marked *