Understanding the Differences and Uses of map and forEach in JavaScript

Understanding the Differences and Uses of map and forEach in JavaScript

Both map and forEach are methods used to iterate over elements in an array, but they are used for different purposes.

map is used to create a new array with the results of calling a provided function on every element in the calling array. It returns a new array and does not modify the original array.

forEach is used to execute a provided function once for each element in an array. It does not return a new array and does not modify the original array.

For example:


let numbers = [1, 2, 3, 4, 5]


// Using map
let doubleNumbers = numbers.map(function(number) {
? return number * 2;
});
console.log(doubleNumbers); // [2, 4, 6, 8, 10]
console.log(numbers); // [1, 2, 3, 4, 5]


// Using forEach
let sum = 0;
numbers.forEach(function(number) {
? sum += number;
});
console.log(sum); // 15
console.log(numbers); // [1, 2, 3, 4, 5];        

You can use map when you want to transform an array and return the new array, while you can use forEach when you want to execute a function on each element of an array and don't need to return a new array.

要查看或添加评论,请登录

Jack Mtembete的更多文章

社区洞察

其他会员也浏览了