The map() method in JavaScript is used to create a new array by applying a function to each element in the original array. It calls the specified function once for each element in the array and returns a new array with the results.
Syntax
array.map(callback(currentValue, index, array));
Parameters
Parameters | Descriptions |
---|---|
callback() | A function to be called for each element in the array. It can take three arguments: currentValue, index, and array. |
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. |
Return Value
Return Type | Description |
---|---|
Array | A new array with each element being the result of the callback function. |
Example 1: Using map() to Double Each Element
This code demonstrates how to use the map()
method to create a new array with each element doubled.
let Arr = [1, 2, 3, 4, 5]; let doubled = Arr.map(num => num * 2); console.log(doubled);
Output:
[ 2, 4, 6, 8, 10 ]
Example 2: Using map() with Index
You can also access the index of the current element within the map()
function.
let Arr = [1, 2, 3, 4, 5]; let squared = Arr.map((num, index) => num * index); console.log(squared);
Output:
[ 0, 2, 6, 12, 20 ]
Example 3: Using map() with an Object Array
The map()
method can be used with an array of objects to extract a specific property.
let students = [ { name: 'Alice', age: 20 }, { name: 'Bob', age: 22 }, { name: 'Charlie', age: 21 } ]; let names = students.map(student => student.name); console.log(names);
Output:
[ "Alice", "Bob", "Charlie" ]
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
1 | 12 | 1.5 | 9.5 | 3 |