JS Map
Review of JavaScript's map()
method
02/20/2025
read time:2 mins
Brushing up on JavaScript’s .map()
method today. I realized I was asking prospective hires at work a question about .map()
that I didn’t know the answer to myself—not off the top of my head, at least.
The .map()
method on an array in JavaScript creates a new array, filled with the results of running a provided callback function on each array element. So [1,2,3].map(x => x*2)
returns [2, 4, 6]
.
.map()
can take two parameters: the callback function and a value to use as this
when executing the callback function.
The callback function has three optional parameters: element, index and array. The element is the array element you manipulate with each iteration. The index is the (zero-based) count of how many iterations have happened so far. The array is the original array.
.map()
callback parameter
element parameter
console.log([1,2,3].map(x => x*2))
outputs: [2, 4, 6]
// [1*2, 2*2, 3*2]
index parameter
console.log([1,2,3].map((x,i) => x*i))
outputs: [0, 2, 6]
// [1*0, 2*1, 3*2]
array parameter
console.log([1,2,3].map((x,i,arr) => {
console.log(arr)
return x*i
}))
outputs:
[ 1, 2, 3 ]
[ 1, 2, 3 ]
[ 1, 2, 3 ]
[ 0, 2, 6 ]
.map()
thisArg
parameter
ChatGPT gave me this nice example of a simple use of the thisArg
parameter. In this exapmle, multiplier
is the thisArg
value:
const multiplier = {
factor: 2,
multiply(num) {
return num * this.factor;
}
};
const numbers = [1, 2, 3];
const doubled = numbers.map(function(num) {
return this.multiply(num);
}, multiplier); // Passing multiplier as thisArg
console.log(doubled); // outputs [2, 4, 6]
Sources
- MDN, “Array.prototype.map()”. accessed 2/20/25
- I used ChatGPT 4o for the
thisArg
example. accessed 2/20/25