Last Updated: February 25, 2016
·
957
· peterssonjesper

A neat foreach-loop in Javascript

It's commonly that I come across code looking something like this:

var items = [1, 2, 3, 4, 5];
for(var i in items) {
  var item = items[i];
  // Do something with item
}

A more functional approach would simply be to do like this:

var items = [1, 2, 3, 4, 5];
items.map(function(item) {
  // Do something with item
});

In many cases I believe that this is a better choice. Shorter, easier to read, etc.

However, remember that in Javascript are primitives datatypes (such as integers, strings, etc.) referred to using call-by-copy. Hence an assignment to item within the loop would not work. If you are looping over objects on the other hand, then call-by-reference will used and an assignments would work just fine.

4 Responses
Add your response

  1. You shouldn't be using the for...in loop to iterate over arrays, it's made for iterating objects.
  2. ES5 defines Array.forEach() function specifically to iterate over an array if you don't want to use the regular for loop.
over 1 year ago ·

The for...in loop can iterate over any kind of enumerable object, including dictionaries and arrays.

The Array.forEach() is nice, but it's not supported in older browsers like IE8 and below.

over 1 year ago ·

@peterssonjesper, yes, I know that for...in loop can iterate over any kind of enumerable object but there are several reasons why it's discouraged to use it for an array.

Array.map() isn't supported by IE8 either so it's no better than Array.forEach for simple iteration.

over 1 year ago ·

You're missing the main point in your example: map returns a new array, so in your example items has still the same values as before. You have to assign the result of map to a new variable.

var items = [1, 2, 3, 4, 5];
var newItems = items.map(function(item) {
  // Do something with item
});
over 1 year ago ·