The map method in JavaScript is an array method used to create a new array by applying a provided function to each element in the original array. It’s particularly useful when you need to transform or process each element and return a new array with the results, leaving the original array unchanged.
Syntax:
const newArray = array.map(function(element, index, array) {
// Return transformed element here
}, thisArg);
element: 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): A value to use as this
when executing the callback function.
Characteristics of map
1. Returns a New Array: The map
method returns a new array containing the results of applying the provided function to each element of the original array.
2. Original Array Unchanged: The original array remains unchanged after the map
operation.
3. Transforms Each Element: The function provided to map
transforms each element in the array, and the result of this transformation is stored in the new array.
4. Iterates Over Every Element: The function passed to map
is called for every element in the array, even if the element is undefined
, null
, or an empty slot.
5. Chaining: Since map
returns a new array, you can chain other array methods like filter
, reduce
, etc., on the result.
Example:
const numbers = [1, 2, 3, 4];
const updatedNumbers = numbers.map(num => num * 5);
console.log(updatedNumbers); // Output: [5, 10, 15, 20]
console.log(numbers); // Output: [1, 2, 3, 4] (original array is unchanged)
Extracting Specific Properties:
const users = [
{name: 'John', age: 39},
{name: 'Tom', age: 38},
{name: 'Mathew', age: 35}
];
const names = users.map(user => user.name);
console.log(names); // Output: ['John', 'Tom', 'Mathew']