JavaScript map()
the map()
method is also used for iterating over array elements, but its main purpose is to create a new array by applying a provided function to each element of the original array. It returns a new array with the results of applying the function to each element.
Syntax:
map((currentElement, indexOfElement, array) => { ... } );
Parameters:
callback
: A function to execute for each element, taking three arguments:currentValue
: The current element being processed in the array.index
(optional): The index of the current element being processed.array
(optional): The arraymap
was called upon.
thisArg
(optional): Value to use asthis
when executingcallback
.
Return Value:
A new array with the results of calling the provided function on every element in the array.
Example: In this example, we are using map().
Javascript
const numbers = [1, 2, 3, 4]; const doubledNumbers = numbers.map((number) => { return number * 2; }); console.log(doubledNumbers); |
[ 2, 4, 6, 8 ]
Difference between forEach() and map() loop in JavaScript
When we work with an array, it is an essential step to iterate on the array to access elements and perform some kind of functionality on those elements to accomplish any task. For this loops like ForEach() and Map() are used. In this article, we are going to learn the difference between the forEach() and map() loops in JavaScript.