Implement map on a Prototype- whats that code means?

Tell us what’s happening:
I don’t understand the code used here.

// the global Array
var s = [23, 65, 98, 5];

Array.prototype.myMap = function(callback){
  var newArray = [];
  // Add your code below this line
  this.forEach(a => newArray.push(callback(a)));
  // Add your code above this line
  return newArray;

};

var new_s = s.myMap(function(item){
  return item * 2;
});

Your code so far


// the global Array
var s = [23, 65, 98, 5];

Array.prototype.myMap = function(callback){
  var newArray = [];
  // Add your code below this line
  for ( let i =0; i <callback.length; i++){
    newArray.push(callback[i]);
  }
  // Add your code above this line
  return newArray

};

var new_s = s.myMap(function(item){
  return item * 2;
});

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/implement-map-on-a-prototype

could you please elaborate on what you don’t understand? what part are you missing?

1 Like

Hi ieahleen!
this part:
this.forEach(a => newArray.push(callback(a)));

why we used this?
and what a means ?
and what => used for ?

and the code i tried in the example doesn’t work ?

Thank you for your time and help!

this refers to an execution context object, in the case of a prototype method, it refers to the instance object of the prototype you’re adding the method to (Array for this example) so in summary: this equals to whatever array you’re calling the new method on, so if you do:

var arr = [23, 65, 98, 5];

arr.map(...)

inside the body of Array.prototype.map(), this refers to [23, 65, 98, 5]


=> is an arrow function; there is no way you could have done this challenge without going through the ES6 lessons first (unless the code comes from somewhere else or FCC messed up with the lesson order).


Same as with the previous arrow function, the a is the argument of the arrow function and it refers to each item of the array you call forEach on as per:

1 Like

wow i feel like my brain is lighting now hehe. yes i have passed by => function but i was wondering if its same one :slight_smile:
Great explanation Luishendrix92! really helpful for me and everyone reading to get help, thanks!