← Back to libraryQuestion 166 of 468
🧩JavaScript CodingAdvanced

Polyfill Array.prototype.map

📌 Definition:

Reimplement the map method (as a standalone function or on the prototype) to understand how higher-order array methods work.

📖 Detailed Explanation:

map returns a new array where each element is callback(element, index, array). It does not mutate the source and skips nothing for dense arrays. The callback receives three arguments.

💻 Solutions:
Array.prototype.myMap = function (callback, thisArg) {
  const result = [];
  for (let i = 0; i < this.length; i++) {
    if (i in this) {
      result.push(callback.call(thisArg, this[i], i, this));
    }
  }
  return result;
};
// [1,2,3].myMap(x => x * 2) -> [2,4,6]
🔑 Key Points:
  • Returns a NEW array; never mutates the source
  • Callback gets (value, index, array)
  • call(thisArg, ...) honors the optional thisArg
  • i in this skips holes in sparse arrays
🌍 Real-World Example:

Reimplementing map/filter/reduce demonstrates you understand callbacks and immutability — the foundation of functional data pipelines used everywhere in test utilities.

🎯 Scenario-Based Interview Question:

A candidate's myMap forgets to pass the index to the callback. Which real-world map usage breaks?