Alternative for \"for...in\" loop


/ Published in: JavaScript
Save to your folder(s)

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.

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.