Neither approach is always better, it depends on the situation, and perhaps as much on what you feel comfortable with.
For one, when using map
the code gets a bit clearer. You see the output as a result of an expression:
var added = arr.map(function(e){
return e + 1;
});
When using a for
loop it's not as obvious where the output ends up:
var added = [];
for (var i = 0; i < arr.length; i++) {
added.push(arr[i] + 1);
}
This approach fits better for functional results (e.g. using map
or filter
to produce a new set), using forEach
doesn't have that exact benefit.
A drawback of the functional approach is that the callback function gets its own context. If you are using it in a method, you need to bind the callback function to get the right context:
var added = arr.map(function(e){
return e + this.change;
}.bind(this));
Anyway, often the situation is more complex than simple examples like this. Then whatever approach you choose won't have that much impact either on performance or readability.