Javascript 1.8 forEach – supported in Safari, Firefox and beyond


If you don’t have to support IE, you can start taking advantage of JavaScript 1.8 features such as the forEach construct. It’s nicer than a conventional for loop when you are iterating over every item in an array.

console.log('The Beatles:');
['john','george','ringo','paul'].forEach(function(beatle, i) {
   console.log("name: " + beatle + "\n" + i);
});

// Result:
/*
 * The Beatles:
 * name: john 0
 * name: george 1
 * name: ringo 2
 * name: paul 3
*/

This is a great technique when creating iPhone web apps. Since the iPhone sports a modern Webkit browser, we can use forEach.

Compare the traditional for with forEach:

// Oldschool way using for
var beatles = ['john','george','ringo','paul'];
for (var i = 0, l = beatles.length; i < l; i++) {
    console.log("name: " + beatles[i] + "\n" + i);
}

// Newschool JavaScript 1.8 forEach
['john','george','ringo','paul'].forEach(function(beatle, i) {
    console.log("name: " + beatle + "\n" + i);
});

They are functionally the same, but as you can see, the newschool way is much cleaner.

Share and Enjoy:
  • Print
  • Digg
  • StumbleUpon
  • Slashdot
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Share/Bookmark

  1. No comments yet.
(will not be published)