Prototype / Polyfill function for JavaScript Array map
The `map()` function is a built-in method in JavaScript that is used to create a new array by performing a given operation on each element of the original array. The prototype function for `map()` can be written as follows:
Array.prototype.myMap = function(callback) {
let result = [];
for(let i=0; i<this.length; i++) {
result.push(callback(this[i], i, this));
}
return result;
}
In this function, we have created a new prototype method called `myMap()` for the `Array` object, which takes a callback function as an argument. The callback function is the operation that will be performed on each element of the original array.
Get Bharathikannan Ramakrishnan’s stories in your inbox
Join Medium for free to get updates from this writer.
Inside the function, we initialize an empty array called `result` that will hold the mapped values. We then loop through each element of the original array using a `for` loop. For each element, we call the `callback` function with three arguments: the current element, its index, and the original array. The `callback` function returns the mapped value, which we push to the `result` array.
Finally, we return the `result` array, which contains all the mapped values.
This prototype function can be used like the built-in `map()` method, as shown below:
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.myMap(num => num * 2);
console.log(doubled); // Output: [2, 4, 6, 8, 10]In this example, we use `myMap()` to double each element of the `numbers` array and store the results in a new array called `doubled`. The output is then printed to the console.




