Posted By

hellowouter on 03/30/12


prototype loop for order sequential

Versions (?)

Alternative for "" loop

 / Published in: JavaScript


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 "" loop is no option since the loop will also iterate over the new prototype properties.

  1. for (var i = 0, item; item = a[i++];) {
  2. // Do something with item
  3. }

Report this snippet  

You need to login to post a comment.