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 array map was called upon.
  • thisArg (optional): Value to use as this when executing callback.

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);


Output

[ 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.

Similar Reads

JavaScript forEach()

The forEach() method is primarily used for iterating over array elements and executing a provided function once for each array element. It doesn’t create a new array and doesn’t return anything. It’s mainly used when you want to perform an operation on each element of the array without creating a modified version of the array....

JavaScript map()

...

Differences between forEach() and map() methods

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....