JavaScript foreach Equivalent

Many times I’ve been asked about the equivalent to the Java foreach loop in JavaScript. For example, in Java:

Unfortunately the same thing does not exist in JavaScript.
A similar syntax is the for x in y expression, but this is not the same thing!

This will alert each of the keys in the object. The “for in” loop in JavaScript loops through object keys, not lists.

If you do:

This will log “0”, “1”, “2”, “3”, “4”, which isn’t expected at all.

Every array in JavaScript is internally an object mapping each index in the array to each member in the array. So when you do a “for in” loop in JS, you’re really telling it to loop through all of the keys in the array object, which corresponds to all of the indices, not the values.

Jquery.each(), goog.array.foreach(), and Array.forEach

The closest I’ve come to a true foreach loop in JS is the Google Closure goog.array.foreach() function or the Jquery.each() function. In modern browsers, you can use the builtin Array.forEach to accomplish the same thing.

For example

But, if you’re in the middle of an object, you have to be careful about the “this” context within the function call, and you might have to call .bind(this) to set the scope correctly.

What I Use

Because of this problem, I usually find myself using a regular for loop when iterating over arrays.

Yes, it’s more verbose, but I find it perfectly clear.

More Potential Pitfalls

Now, the issue with these occurs if you’re dealing with callbacks within the for loop, and you need to bind variables defined within the loop to the callback function.

Let’s look at an example 

The result: “undefined” is printed 4 times, instead of the members of the array.

Why?

The callback inside of setTimeout does not capture the value of i on each iteration of the loop.

Instead, we bind up 4 callbacks, 1 for each iteration of the loop, each to start 100 ms later.

The loop has finished executing before a single callback has been invoked.

When each of the callbacks is then called, it uses the last value of i, which is 4. arr[4] is undefined, since it’s one beyond the last index in the array.

To fix this problem, we can do 

This captures the value of i during each iteration of the loop and passes it into the function, leading to the output we expect.