Saturday, March 15, 2008

A clean javascript foreach loop

Here's a somewhat unusual way to write a foreach loop, using the old plain vanilla for statement:

var items = ["Apple", "Banana", "Strawberry"];
for (var item, i = 0; item = items[i]; i++) {
  console.log(item);
}

There are three advantages for using this syntax over calling Array.forEach() or whatever other library foreach implementation:

  1. There's no function call overhead. I've already talked about this here
  2. You can use break and continue statements:
    var items = ["Apple", "Banana", "Dice", "Strawberry"];
    for (var item, i = 0; item = items[i]; i++) {
      if (item == "Dice") continue;//no dice!
      console.log(item);
    }
    
  3. You have full control over the iterator cursor:
    var items = ["John", "Apple", "Mary", "Banana", "Jane", "Strawberry"];
    //for every second item, starting from the second item
    for (var item, i = 1; item = items[i]; i += 2) {
      console.log(item);
    }
    

One word of caution though: the "item" variable I declared is still in scope after the loop terminates, unlike a foreach loop that calls a function.

No comments:

Post a Comment