DEV Community

Cover image for JavaScript Array Methods: forEach(), map(), and flatMap()
Saravanan Lakshmanan
Saravanan Lakshmanan

Posted on

JavaScript Array Methods: forEach(), map(), and flatMap()

====================================================

1. forEach()

What is forEach()?

forEach() is used to execute a function once for every element in an array.

It is mainly used when you want to:
• Print values
• Update variables
• Call another function
• Perform some action for every element

Important:
forEach() does NOT return a new array.


Syntax

array.forEach(function(value, index, array) {
// code
});

Parameters:

  1. value -> Current element
  2. index -> Current index
  3. array -> Original array

Example 1

let numbers = [10, 20, 30];

numbers.forEach(function(value){
console.log(value);
});

Output:
10
20
30


Example 2

let numbers = [10, 20, 30];

numbers.forEach(function(value, index, array){
console.log(value, index, array);
});

Output:
10 0 [10,20,30]
20 1 [10,20,30]
30 2 [10,20,30]


Internal Logic of forEach()

let numbers = [10,20,30];

function display(value){
console.log(value);
}

for(let i = 0; i < numbers.length; i++){
display(numbers[i]);
}

This is approximately how forEach() works internally.


Return Value of forEach()

let numbers = [10,20,30];

let result = numbers.forEach(function(value){
return value * 2;
});

console.log(result);

Output:
undefined

Even if you return something, forEach() ignores it.


When to Use forEach()

✔ Printing values
✔ Calling functions
✔ Updating variables
✔ Executing code for every element

✘ Not suitable when you need a new array

====================================================

2. map()

What is map()?

map() creates a NEW ARRAY by transforming every element of the original array.

Original array remains unchanged.


Syntax

array.map(function(value, index, array){
return newValue;
});


Example 1

let numbers = [10,20,30];

let result = numbers.map(function(value){
return value * 2;
});

console.log(result);

Output:
[20,40,60]


Original Array Remains Same

console.log(numbers);

Output:
[10,20,30]


Internal Logic of map()

let numbers = [10,20,30];

let newArray = [];

for(let i = 0; i < numbers.length; i++){
newArray.push(numbers[i] * 2);
}

console.log(newArray);

Output:
[20,40,60]

This is approximately how map() works internally.


Example 2

let numbers = [1,2,3];

let result = numbers.map(function(value){
return "Number: " + value;
});

console.log(result);

Output:
[
"Number: 1",
"Number: 2",
"Number: 3"
]


When to Use map()

✔ Transforming data
✔ Modifying values
✔ Creating a new array
✔ Preparing data for UI

Example:
10 → 20
20 → 40
30 → 60

====================================================

Difference Between forEach() and map()

forEach()

• Iterates through array
• Does not return new array
• Used for actions
• Return value ignored

map()

• Iterates through array
• Returns new array
• Used for transformations
• Returned values collected

Example:

let numbers = [10,20,30];

numbers.forEach(function(value){
console.log(value * 2);
});

Output:
20
40
60


let numbers = [10,20,30];

let result = numbers.map(function(value){
return value * 2;
});

console.log(result);

Output:
[20,40,60]

====================================================

3. flatMap()

What is flatMap()?

flatMap() = map() + flat()

It first transforms each element and then flattens the result by one level.


Why Do We Need flatMap()?

Consider:

let numbers = [1,2,3];

let result = numbers.map(function(value){
return [value, value * 10];
});

console.log(result);

Output:

[
[1,10],
[2,20],
[3,30]
]

Notice that map() creates nested arrays.


Using flat() After map()

let result = numbers
.map(function(value){
return [value, value * 10];
})
.flat();

console.log(result);

Output:

[1,10,2,20,3,30]


Using flatMap()

let numbers = [1,2,3];

let result = numbers.flatMap(function(value){
return [value, value * 10];
});

console.log(result);

Output:

[1,10,2,20,3,30]

flatMap() performs map() and flat() together.


Visual Representation

Original Array:

[1,2,3]

map():

[
[1,10],
[2,20],
[3,30]
]

flatMap():

[
1,10,
2,20,
3,30
]


Understanding Square Brackets []

Example:

let result = [1,2,3].flatMap(function(x){
return [x, x * 10, 40];
});

Iteration 1:

x = 1

return [1,10,40]

Iteration 2:

x = 2

return [2,20,40]

Iteration 3:

x = 3

return [3,30,40]

map() would produce:

[
[1,10,40],
[2,20,40],
[3,30,40]
]

flatMap() automatically converts it into:

[
1,10,40,
2,20,40,
3,30,40
]


Why Can't We Write?

return x, x * 10, 40;

Because JavaScript uses the comma operator.

Example:

function demo(){
return 10,20,30;
}

console.log(demo());

Output:
30

Only the LAST value gets returned.

Therefore:

return x, x * 10, 40;

returns only:

40

To return multiple values, use an array:

return [x, x * 10, 40];


Does flatMap() Also Pass value, index, array?

YES.

Just like forEach() and map(), flatMap() also passes:

(value, index, array)

Example:

let numbers = [10,20,30];

numbers.flatMap(function(value, index, array){

console.log(value);
console.log(index);
console.log(array);

return [value];
Enter fullscreen mode Exit fullscreen mode

});

References:
https://www.w3schools.com/js/js_array_iteration.asp#mark_foreach
https://www.geeksforgeeks.org/javascript/javascript-array-methods/

Top comments (0)