JavaScript does many things well, but one area I’ve always had trouble with is the array and array-manipulation department. For example, this weekend I was working on a project that required me to iterate through a JavaScript array and peform a set of functions on the values within. In PHP, that would have looked something like this:
$myArray = array("item 1", "item 2", item 3");
foreach($myArray as $item) {
$item = "Do Something Here";
}Nice and simple, right? All we’re doing is iterating through the array with the foreach() construct and replacing each item with the phrase “Do Something Here,” but you can see how this could/would expand. A similar construct exists in Perl, another language I grew up on.
But JavaScript lacks a specific “foreach” statement, which trips me up every time. So how do we fake it?
Plain-Jane JavaScript Foreach
In JavaScript, we make use of the for() loop construct to fake a foreach scenario. It looks something like this:
myArray = new Array("item 1", "item 2", "item 3");
for(i=0; i<myArray.length; i++) {
myArray[i] = "Do Something Here".
}This lets us loop over our array and do something with each item in turn. It’s not pretty, but it technically does the trick.
jQuery Foreach Loops
As with many things in the JavaScript world, jQuery makes the concept of a foreach loop simpler. To iterate over an array in jQuery, we’ll use the jQuery.each() (or in shorthand, $.each()) function.
Note: This is a different function than the more commonly known $(whatever_element).each(), and has slightly different usage!
The jQuery $.each() function works like this:
myArray = new Array("item 1", "item 2", "item 3");
$.each(myArray, function() {
this = "Do Something Here";
});In short, we pass the $.each() function two parameters: the first is the array we want to iterate over, and the second is the function we want to perform on that array. Within the function, we simply refer to the current item as “this,” which is pretty standard fare.
I prefer the jQuery functionality for two reasons:
- It reads slightly more like a PHP foreach statement, and
- I’m generally loading jQuery anyway, so there’s no harm in using it.
Your needs may vary – I’m not suggesting loading jQuery on an otherwise framework-free page just to make array loops easier. But if you’ve already got jQuery loaded, this might save you a bit of time (and in my case, frustration).


On January 21, 2010
3:50PM
RobShaver said:
Call me old fashion but I’ll take the “for” loop over a library call every time. Why? Because 1) well … no library needed, 2) I can see all the moving parts and I understand it completely and 3) I don’t have to write an anonymous function. If “foreach” is in the language like it is in PHP, then I’d use it.
Maybe it’s because I’ve been writing code for 30 years and old habits die hard. I’d kind of like the standard “for” loop is hard-wired into my spine by now.
Not to say you shouldn’t write articles like this. Gives everybody food for thought. Thanks for writing it.
On January 21, 2010
10:59PM
Brandon said:
Technically, if you are just needing a simple foreach in JavaScript you can use for(obj in ary). So your JavaScript example would produce:
myArray = new Array(“item 1″, “item 2″, “item 3″);
for(i in myArray){
myArray[i] = “Do Something Here”.
}
Granted, this has some issues if you are using a library that mucks with the Array.prototype, but it is technically a foreach.
On January 22, 2010
9:38AM
Rob Glazebrook said:
There’s nothing technically wrong with the “for” loop structure. I just have a hard time remembering it. I’m guessing if I’d learned JavaScript before PHP I’d feel the “foreach” loop was overkill or something. :)
On January 22, 2010
9:40AM
Rob Glazebrook said:
That’s a good point, Brandon. I was originally going to lead with that structure for my JavaScript example, but I discovered it has issues when running with jQuery. At least, I assume that was the problem: the array[i] syntax was returning a function, not a value. So I gave that line of programming up for now and went with the more well-known syntax.
On January 22, 2010
2:04PM
Chris Coyier said:
I was always told that you should set a variable to the myArray.length first, that way it doesn’t have to calculate that number on every iteration. And for some reason, ++i is faster that i++ I’ve been told, but I have no idea why.
On January 23, 2010
11:09AM
tog000 said:
In my opinion, Mootools has the most powerful “foreach” emulation for Javascript:
myArray = new Array(“item”, “item”, “item”);
myArray.each(function(element,index){
myArray[index] = element+index;
})
This will produce: {“item0″,”item1″,”item2″}
On January 24, 2010
2:58PM
mike stevens said:
Very nice article. The cross language examples are insightful
On January 24, 2010
3:09PM
Frank Schenk said:
What’s wrong with Brandons example? It works perfectly and it doesn’t require a bloated library like jquery.
for() is btw much faster than foreach in php, if the maximum number is given as variable, not as function, thats the problem with foreach, as it always has to check the content of the given array.
so:
$max = count( $array);
for( $i=0; $<$max; $i++){
$array[$i] = 'Do whatever you want to do';
}
is way faster than foreach.
cheers, Frank
On January 25, 2010
10:27AM
Rob Glazebrook said:
Hi Frank,
My only concern with Brandon’s example is that if you ~do~ happen to be using a library like jQuery (and that’s a growing percentage of the web populace), that structure can give you problems. I tested it for the purposes of this article and array[i] was returning a function, not the array string I was expecting.
So, if you’re not using jQuery or a similar framework, and never plan to use a JavaScript framework on your pages, by all means go with that system. But if you’re already using jQuery or another framework for something else, you may run into problems!
On February 03, 2010
7:29AM
Lee Kowalkowski said:
You only need to cache the array length if the array is actually a DOM collection (e.g. element.childNodes). JS for(… in …) won’t work cross browser over DOM collections anyway – because some browsers include the length property and will use that as one of the iterations.
You need for(… in …) to iterate through properties of an object though, therefore I’d never advise modifying Array.prototype. E.g:
var a = [];
a["key1"] = “value1″;
a["key2"] = “value2″;
.. if Array.prototype has been modified, it makes things more difficult.