🗺️ Array.prototype.map() Polyfill
Category: js / polyfills
Difficulty: hard
Interview Importance: 🔴 Critical — One of the most frequently asked polyfill questions. Tests understanding of array methods, this binding, callbacks, and prototype extension. 1️⃣ What is Array.map()? Array.prototype.map() creates a new array populated with the results of calling a provided function on every element in the calling array. [code example] Key Characteristics Description New array of same length Mutates original? Yes (skips holes) Accepts thisArg? 2️⃣ Why Know the Polyfill? Interview staple — Asked frequently to test JavaScript fundamentals Understand internals — Know how native methods work under the hood Edge cases — Learn about sparse arrays, this binding, callback signature Build confidence — If you can implement map, you can implement any array method 3️⃣ Native API Signature [code example] Description Function called for each element currentValue Index of current element array Value to use as this inside callback (optional) | 4️⃣ Implementation Basic Implementation ```javascript Array.prototype.myMap = function(callback, thisArg) { // Validation: callback must be a function if (typeof callback !== 'function') { throw new TypeError(callback + ' is not a function'); } const result = []; for (let i = 0; i < this.length; i++) { // Skip holes in sparse arrays (critical!) if (this.hasOwnProperty(i)) { // Call callback with: thisArg, currentValue, index, array result.push(callback.call(thisArg, this[i], i, this)); } }...