In JavaScript, both map() and forEach() are array methods used to iterate over the elements
of an array. They are similar in that they allow you to perform operations on array elements,
but they differ in their return values and how they handle the result of the operation.
map():
The map() method is used to create a new array by applying a transformation
function to each element in the original array. It returns a new array with
the same length as the original array, where each element is the result of
applying the transformation function to the corresponding element of the
original array.
Code:
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map((number) => number * number);
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]
console.log(numbers)
Output:
[ 1, 4, 9, 16, 25 ]
[ 1, 2, 3, 4, 5 ]
Explanation:
In this example, the map() method applies the transformation function
(number) => number * number to each element of the numbers array,
resulting in a new array squaredNumbers that contains the squares
of the original numbers.
forEach():
The forEach() method allows you to iterate over each element of an
array and perform a specified action for each element. Unlike map(), forEach()
does not create a new array. It simply executes a callback function for each
element in the array without modifying the original array.
Code:
const numbers = [1, 2, 3, 4, 5];
numbers.forEach((number) => {
console.log(number); // Output: 1, 2, 3, 4, 5
});
console.log(numbers)
Output:
1
2
3
4
5
[ 1, 2, 3, 4, 5 ]
Explanation:
In this example, the forEach() method executes the callback function
(number) => console.log(number) for each element of the numbers array,
logging each number to the console.
To summarize:
Use map() when you want to transform each element of an array and create a new
array with the transformed values.Use forEach() when you want to perform a
specific action for each element of an array without creating a new array.
Both methods are useful in different scenarios, and the choice depends on
whether you need to create a new array or simply perform an action on each
element.
No comments:
Post a Comment