Return to Snippet

Revision: 56486
at March 30, 2012 19:10 by hellowouter


Initial Code
for (var i = 0, item; item = a[i++];) {
    // Do something with item
}

Initial URL
https://developer.mozilla.org/en/A_re-introduction_to_JavaScript#Arrays

Initial Description
We are setting up two variables. The assignment in the middle part of the for loop is also tested for truthfulness — if it succeeds, the loop continues. Since i is incremented each time, items from the array will be assigned to item in sequential order. The loop stops when a "falsy" item is found (such as undefined).

Note that this trick should only be used for arrays which you know do not contain "falsy" values (arrays of objects or DOM nodes for example). If you are iterating over numeric data that might include a 0 or string data that might include the empty string you should use a standard for loop.

Note that if someone added new properties to Array.prototype, using a "for...in" loop is no option since the loop will also iterate over the new prototype properties.

Initial Title
Alternative for \"for...in\" loop

Initial Tags
order

Initial Language
JavaScript