Array.prototype.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 and array to the map callback.
  • Calling the map callback with the correct this if thisArg 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 to this.

Resources

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ayesha Malik

Ayesha Malik

I’m a full-time software engineer who loves sharing knowledge to help others become better developers.