The .map()
method is a built-in JavaScript method that allows you to create a new array with the results of calling a provided function on every element in the original array. It essentially creates a new array by performing an operation on each element of the original array.
Here’s the basic syntax of the .map()
method:
array.map(function(currentValue, index, arr), thisValue)
function(currentValue, index, arr)
is the function that will be executed on every element of the array.currentValue
is the value of the current element being processed.index
is the index of the current element being processed.arr
is the original array that the.map()
method was called on.thisValue
is an optional parameter that can be used to set thethis
value in the callback function.
Here’s an example of how to use the .map()
method:
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(function(number) {
return number * number;
});
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]
In this example, we have an array of numbers. We then use the .map()
method to create a new array called squaredNumbers
, which contains the squares of each number in the original array…