The map()
method in JavaScript works as follows:
- It creates a new array with the results of calling a provided function on every element in the calling array.
- The provided function is called with three arguments: the current element, the index of the current element, and the array map was called upon.
- The
this
value provided as a second argument tomap()
is used asthis
when executing each callback. - It does not mutate the original array.
Here's a simple example:
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(function(number) {
return number * 2;
});
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
In this example, map() is called on the numbers array and returns a new array doubledNumbers where each number is doubled.
The syntax for the map() method in JavaScript is as follows:
array.map(callbackFunc(currentValue, index, arr), thisValue)
Here's what each parameter means:
callbackFunc(currentValue, index, arr)
: A function to be called for each element in the array. This function accepts three arguments:currentValue
: The current element being processed in the array.index (optional)
: The index of the current element being processed in the array.arr (optional)
: The arraymap
was called upon.
thisValue (optional)
: A value to use asthis
when executing the callback function.
const numbers = [1, 2, 3, 4, 5];
Array.prototype.map = function(callbackFunc){
const newArr = []
for(let i=0; i<this.length; i++){
newArr.push(callbackFunc(this[i]))
}
return newArr;
}
console.log(numbers.map(doubledNumbers)) // Output: [2, 4, 6, 8, 10]