Last Updated: October 04, 2020
·
4.488K
· rykus0

Simplified Descending for Loop

Most JS devs know that it's more efficient to avoid calling Array.length on each iteration of a loop.

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

There are several ways around this. Most common is to cache the length.

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

I find it a bit more elegant to use a descending iterator, when I can.

for( i = myArray.length - 1; i >= 0; i-- )

This can be further simplified to

for( i = myArray.length; --i >= 0; )

or better yet

for( i = myArray.length; i--; )

Novice devs should be able to figure out what's going on, but always use caution when deviating from standard syntax.

Related protips:

javascript foreach