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:

javascript
1
2
3
4
5
6
7
let array = ['1', '2', '3']
for (var i = 0; i < array.length; i += 1) {
console.log(Number(array[i]));
}
//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:

javascript
1
2
3
let newArray = arr.map((currentValue, index, array) => {
// return any element to an new array
})

It contains two parameters: A callback function and a value to use as this when exeuting callback.

javascript
1
2
3
4
5
6
7
8
9
const arr = ['1', '2', '3']

const cb = (str, i, origin) => {
console.log(`${i}: ${Number(str)} / ${origin}`)
};
arr.map(cb);
// 0: 1 / 1,2,3
// 1: 2 / 1,2,3
// 2: 3 / 1,2,3

callback function can be used as:

javascript
1
2
3
arr.map((str) => {
console.log(Number(str))
})

this result of map() does not equal to original array.

javascript
1
2
3
4
const arr = [1];
const newArray = arr.map(d => d);

arr === newArray; // false

We can also sending thisArg back to map as an objective.

javascript
1
2
3
4
5
6
7
8
9
10
11
const obj = { name: 'Tom'}

[1].map(function)() {
// {name: 'Tom'}
console.dir(this);
}, obj);

[1].map(() => {
// window
console.dir(this)
}, obj);

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.

As part 2 will continue with forEach funcation