The only difference I see in map and foreach is that map
is returning an array and forEach
is not. However, I don\'t even understand the last line
The essential difference between map
and forEach
in your example is that forEach
operates on the original array elements, whereas map
explicitly returns a new array as a result.
With forEach
you are taking some action with -- and optionally changing -- each element in the original array. The forEach
method runs the function you provide for each element, but returns nothing (undefined
). On the other hand, map
walks through the array, applies a function to each element, and emits the result as a new array.
The "side effect" with forEach
is that the original array is being changed. "No side effect" with map
means that, in idiomatic usage, the original array elements are not changed; the new array is a one-to-one mapping of each element in the original array -- the mapping transform being your provided function.
The fact that there's no database involved does not mean that you won't have to operate on data structures, which, after all, is one of the essences of programming in any language. As for your last question, your array can contain not only numbers, but objects, strings, functions, etc.
The following is based on the official description of Array.prototype.map().
There is nothing that forEach()
can do that map()
cannot. That is, map()
is a strict super-set of forEach()
.
Although map()
is usually used to create a new array, it may also be used to change the current array. The following example illustrates this:
var a = [0, 1, 2, 3, 4], mapped = null;
mapped = a.map(function (x) { a[x] = x*x*x; return x*x; });
console.log(mapped); // logs [0, 1, 4, 9, 16] As expected, these are squares.
console.log(a); // logs [0, 1, 8, 27, 64] These are cubes of the original array!!
In the above example, a
was conveniently set such that a[i] === i
for i < a.length
. Even so, it demonstrates the power of map()
, and in particular its ability to change the array on which it is called.
Note1:
The official description implies that map()
may even change length the array on which it is called! However, I cannot see (a good) reason to do this.
Note2:
While map()
map is a super-set of forEach()
, forEach()
should still be used where one desires the change a given array. This makes your intentions clear.
Hope this helped.