Developed By
Gautam Kumar - Full stack developer
DEEP DIVE INTO
In JavaScript, the map() method is a built-in array method used to create a new array by applying a provided function to each element of the original array. It takes a callback function as an argument, which is executed for each element in the array, and the return values of these function calls are used to construct a new array. The map() method does not modify the original array; instead, it returns a new array containing the results of applying the callback function to each element.
Here's the basic syntax of the map() method:
javascriptconst newArray = array.map(callback(currentValue, index, array));
array: The original array on which you want to apply the map() method.
callback: A function that is called for each element in the array. It can take up to three parameters:
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.
The map()
method returns a new array containing the results of applying the callback function to each element in the original array, in the same order.
Here's an example of how the map()
method can be used:
javascriptconst numbers = [1, 2, 3, 4, 5];
// Double each number in the array
const doubledNumbers = numbers.map(function (currentValue) {
return currentValue * 2;
});
console.log(doubledNumbers); // Outputs: [2, 4, 6, 8, 10]
In this example, the map() method is used to create a new array, doubledNumbers, by doubling each element of the numbers array.
The map() method is commonly used for transforming data in an array, such as applying a function to each element to derive a new set of values. It is a functional programming concept that allows for cleaner and more concise code when working with arrays.