Javascript Array.forEach

A quick tip, while it’s fresh on my mind:

If you are writing Javascript for Firefox or XULRunner—or anything supporting Javascript 1.6 technically—then you don’t need to write loops like

  1. for (var i = 0; i < some.object.length; i++) {
  2.     var item = some.object[i];
  3.     …
  4. }

Instead use the generic Array.forEach() function and save yourself from creating a temporary variable. The above is more cleanly written as

  1. Array.forEach( some.object, function(item) {
  2.     …
  3. });

This works for any object which has the length property.

Related posts:

  1. Pitfalls With Optional Arguments
  2. Javascript: Notes on Scoping
  3. Returning Multiple Values
  4. Anonymous Functions With Names?
  5. Scoping in Javascript With ‘Let’
0 Comment   |   Posted in Javascript,Programming Languages,blog by EricR on October 31, 2009