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']
map method – Interview Questions
Q 1: What does the map() method do?
Ans: It creates a new array by transforming each element.
Q 2: Does map() return a new array?
Ans: Yes.
Q 3: Does map() modify the original array?
Ans: No.
Q 4: When should map() be used?
Ans: When transforming array data.
Q 5: Can map() be chained?
Ans: Yes, with other array methods.
map method – Objective Questions (MCQs)
Q1. The map() method is used to ______.
Q2. map() returns a new array of ______ length.
Q3. Does map() change the original array?
Q4. Which method is best for transforming values?
Q5. The callback in map() must return ______.