Nick Riggs, Web Developer

Making stuff up about web development since last week.

6 February 2012

Subscribe to our RSS feed

Posted in JavaScript September 15, 2009

Create “foreach” functionality in JavaScript using an Array prototype function

In Javascript, there is no “foreach” statement.  The closest thing we have is “for” syntax that will loop through all of the keys in a JavaScript object.  Using the “for” syntax, we can access property values from the object, such as:

var myArray = [];

myArray.push("First Item");
myArray.push("Second Item");
myArray.push("Third Item");
myArray.customProperty = "Hello";

for (var item in myArray)
    window.alert(myArray[item]);

While this syntax is great for reflecting, it is not the desired result for a “foreach” statement. The reason is, the code above will return not only the items that were pushed onto the array, but also the custom property and any other properties that we were attached (including functions!).

I have written  a simple Array prototype function to supply “foreach” functionality:

Array.prototype.each = function(callback) {
    var args = [null];
    for (var index = 0; index != this.length; index++) {
        args[0] = index;
        callback.apply(this[index], args);
    }
};

Once I have my prototype function in place, I can write code like the follow:

var myArray = [];

myArray.push("First Item");
myArray.push("Second Item");
myArray.push("Third Item");
myArray.customProperty = "Hello";

myArray.each(function() {
    window.alert(this);
});

Using this new prototype function, ONLY the three items that have been pushed onto the array will be handled by the callback functions (the custom property is ignored). The “this” keyword will point an item in the array. Additionally, there is an index argument in case that’s important to you:

myArray.each(function(index) {
    window.alert(this + " is at index " + index);
});