Differences : Map and Foreach Javascript.
Map :
1. map does not modify the original array.2. map returns a new array with the results of the callback function.
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(number => number * number);
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]
forEach :
1. forEach does not return a new array; it modifies or processes elements in place.2. forEach is used when you do not need to create a new array and only need to perform an action on each element.
3. forEach does not support returning a value.
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(number => console.log(number * 2));
// Output: 2, 4, 6, 8, 10
No comments:
Post a Comment