In JavaScript, the map()
method is used to create a new array by applying a function to each element of an existing array. It takes in a callback function as its argument, which is executed for each element in the array. The callback function can have three arguments: the current element being processed, its index, and the original array.
The basic syntax of the map()
method is as follows:
const newArray = array.map(callback(currentValue, index, array));
Here’s a breakdown of the syntax components:
array
: The original array on which themap()
method is called.callback
: A function that is executed for each element in the array.element
: The current element being processed.index
(optional): The index of the current element being processed.array
(optional): The original array on which themap()
method was called.
JavaScript array map example
Simple example code that demonstrates how to use the map()
method to double each element of an array:
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(function (number) {
return number * 2;
});
console.log(doubledNumbers);
Output:
You can also use arrow function syntax for more concise code:
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(number => number * 2);
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
Do comment if you have any doubts or suggestions on this JS array method topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version