Most famous methods of JavaScript map and forEach, they are existing since ECMAScript 5 (es5).
In this artical, I will put out the major different between JavaScript methods map()
and forEach()
by some useful examples.
What is map() and forEach()
map()
and forEach()
are included in Array.prototype
.
We used to looping through an array like this:
1 | let array = ['1', '2', '3'] |
for()
loop is the first out there since JavaScript populated. for()
loop containes 3 statements: init statement, condition and final statement.
This is a classic way to looping through an Array. But when we get into the ECMAScript 5, those new methods kicks in quickly.
map
What does map()
do is exactly like for()
loop, but map()
will create a new array populated with the results of calling a provided function on every element in the calling array.
The syntax of the map funciton is as showing below:
1 | let newArray = arr.map((currentValue, index, array) => { |
It contains two parameters: A callback
function and a value to use as this
when exeuting callback
.
1 | const arr = ['1', '2', '3'] |
callback
function can be used as:
1 | arr.map((str) => { |
this result of map()
does not equal to original array.
1 | const arr = [1]; |
We can also sending thisArg
back to map
as an objective
.
1 | const obj = { name: 'Tom'} |
Objective obj
is map
‘s thisArg. But the arrow function can not set obj
as its thisArg
because of arrow function is not same as normal function.