what is map in Javascript? and it's polyfill

Aman ChandelAman Chandel
1 min read

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)).

0
Subscribe to my newsletter

Read articles from Aman Chandel directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Aman Chandel
Aman Chandel

I am a full stack web developer with a passion for creating interactive and responsive web applications. I have experience working with JavaScript, React.js, Next.js, Redux, Node.js, Express, HTML, CSS, and Git. I am a quick learner and I am always looking to expand my knowledge and skill set. I am a team player and I am excited to work with others to create amazing applications.