JavaScript map() Method
The map() method is used to transform an array by applying a function to each
element and returning a new array with the modified values.
Syntax
js
Copy
Edit
const newArray = array.map(callback(currentValue, index, array));
Parameters
callback(currentValue, index, array)
currentValue → The current element being processed.
index (optional) → The index of the current element.
array (optional) → The original array.
Returns: A new array with transformed elements.
Examples
Example 1: Doubling Numbers
js
Copy
Edit
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6, 8, 10]
✅ Each element is multiplied by 2, returning a new array.
Example 2: Extracting Property from Objects
js
Copy
Edit
const users = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 22 }
];
const names = users.map(user => user.name);
console.log(names); // Output: ["Alice", "Bob", "Charlie"]
✅ Extracts only the name property from an array of objects.