what is map in Javascript? and it's polyfill
In Javascript, map is a higher order function available on arrays, which is used to transform each and every element of an array by applying a callback function to each element of the existing array.
map does not mutate the original array; it returns a new array.
for example:
const numbers = [1, 2, 3, 4]; const doubled =
numbers.map
(num => num * 2); console.log(doubled); // [2, 4, 6, 8]
Polyfill of map:
//Array.map((num, i, arr)) map takes three agruments current element, index and array.
Array.prototype.myMap = function(cb){
let temp = [];
for(let i = 0; i< this.length; i ++){
temp.push(cb(this[i], i, this));
}
return temp;
}
cb is a callback function which takes three arguments current element(this[i], index of element(i), array(this)).