What is the difference between map and forEach?

const nums = [1, 2, 3];

const doubled = nums.map(n => n * 2);
const result = nums.forEach(n => console.log(n));

console.log(doubled);
console.log(result);

Output:

Tutorials Class - Output Window

1
2
3
[ 2, 4, 6 ]
undefined

Use map when you want a new array. Use forEach when you only want to do something for each item. See Array Methods.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.