1 min readNov 21, 2022
Array.prototype.map
Array.prototype.map returns a new array containing the results of calling a given function on every element of the calling array.
callbackFn: A function to execute for each element in the array. Its return value is added as a single element in the new array.
Pollyfill for map
/**
* @callback callbackFn
* @param {object} [thisArg]
* @return {Array}
*/
Array.prototype.myMap = function (callbackFn, thisArg) {
const len = this.length;
const array = new Array(len);
for (let k = 0; k < len; k++) {
// Ignore index if value is not defined for index (e.g. in sparse arrays).
if (Object.hasOwn(this, k)) {
array[k] = callbackFn.call(thisArg, this[k], k, this);
}
}
return array;
};
- Passing the
index
andarray
to the map callback. - Calling the map callback with the correct
this
ifthisArg
is specified. - Sparse arrays (e.g.
[1, 2, , 4]
). The empty values should be ignored while traversing the array. - The
thisArg
doesn't do anything if the callback is defined as an arrow function as arrow functions don't have their own bindings tothis
.