How To Emulate a Foreach Loop in JavaScript

Published January 21, 2010 by CSS Newbies.

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:

  1. It reads slightly more like a PHP foreach statement, and
  2. 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).