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).

25 Responses

  1. RobShaver (reply)

    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.

    1. Rob Glazebrook (Author) (reply)

      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. :)

  2. Brandon (reply)

    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.

    1. Rob Glazebrook (Author) (reply)

      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.

  3. Chris Coyier (reply)

    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.

  4. tog000 (reply)

    In my opinion, Mootools has the most powerful “foreach” emulation for Javascript:

    myArray = new Array(“item”, “item”, “item”);
    myArray[index] = element+index;

    This will produce: {“item0″,”item1″,”item2″}

  5. Frank Schenk (reply)

    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.

    $max = count( $array);
    for( $i=0; $<$max; $i++){
    $array[$i] = 'Do whatever you want to do';

    is way faster than foreach.

    cheers, Frank

    1. Rob Glazebrook (Author) (reply)

      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!

  6. Lee Kowalkowski (reply)

    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.

  7. Pingback: Mike Capson » Blog Archive » How To Create Simple, Stylish and Swappable Image Captions

  8. Pingback: Saint John Web Design | Informative Computer Solutions » Blog Archive » Running jQuery with Other Frameworks Via noConflict

  9. Pingback: Saint John Web Design | Informative Computer Solutions » Blog Archive » How To Create Simple, Stylish and Swappable Image Captions

  10. Pingback: Saint John Web Design | Informative Computer Solutions » Blog Archive » Build a Bare-Bones WordPress 2.8+ Widget

  11. gman (reply)

    Maybe the wrong place to put this but in answer to Chris’s question

    The difference between i++ and ++i is as follows.

    The meaning of i++ is

    var temp = i; i = i + 1; return temp;

    the meaning of ++i is

    i = i + 1; return i;

    It’s the creation of that temp that *may* take more time. In JavaScript I suspect most modern browsers can optimize away the need for temp unless you are using it. But ++ comes from C/C++ and in C++ the creation of temp might be some complex type and have side effects.

    So, best to just get in the habit of coding what you mean. If you want to increment i then use ++i. If you want to both increment i and get the result before you incremented it than use i++.

  12. Al Jey (reply)

    The most efficient way to loop through array elements is like so:

    var arr=[5,4,3,2,1,0],

    Both variables are local, cached and there is minimum evaluation.
    The only thing to note here is that the loop starts at the end of an array.

  13. Pingback: JavaScript Interview Questions & Answers: YourNextLeap

  14. Paul Mc Galey (reply)

    I’m surprised no-one has pointed out that this doesn’t actually work! Specifically,

    this = “Do Something Here”;

    is illegal and throws an error – you can’t assign to ‘this’, and even if you could, you wouldn’t expect it to modify the original array (as ‘this’ would be a reference to the string object, not into the array). You *can’t* modify an array in-place with jQuery.each().

    If you don’t mind creating a new array and really want to use jQuery you could use like this:

    myArray = new Array(“item 1″, “item 2″, “item 3″);
    myArray = $.map(myArray, function() {
    return “Do Something Here”;

  15. Rob @ Forkoff (reply)

    I’d certainly agree with tog000 on this one. I find MooTools to be my personal favorite JS framework anyway, but regardless, their “.each()” method of traversing arrays is by far the nicest to work with.

  16. Júnior (reply)

    The right way is

    var i, k;
    for ( i = 0, k = var.length; i < k; i++ ) {
    // code;



  17. soundcloud plays buy (reply)

    I am really loving the theme/design of your website.
    Do you ever run into any browser compatibility problems? A few of my
    blog visitors have complained about my site not working correctly
    in Explorer but looks great in Chrome. Do you have any advice
    to help fix this issue?

  18. Pingback: Snippet – C#, JavaScript, jQuery, Underscore ForEach Loops | DevDays®

  19. James (reply)

    Why not just use a javascript forEach loop? –

    var array = [ 1, 2, 3 ];
    array.forEach( function( number, index ){
    /* number represents the value, call it whatever ya want */

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>