Help me Understand: Implement map on a Prototype

Tell us what’s happening:
Okay so I’m trying to make sure that I understand what is happening with these functions and not just accepting that it does work. For this reason I was very pleased to see this lesson that breaks down the Array.prototype.map.

I want to check my understanding of the order of events in the code:

  • The loop goes through the first time and i = 0
  • That brings 23 down into the function and it looks like this: newArray.push(callback(23));
  • callback refers to the word function down below in s.myMap(function(item)and 23 becomes the item that gets multiplied
  • Finally the result of 23 * 2 is pushed to the newArry

I think I still struggle to understand what is happening with this section of the code:

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

Your code so far


// The global variable
var s = [23, 65, 98, 5];

Array.prototype.myMap = function(callback){
var newArray = [];
// Only change code below this line
for (let i = 0; i < this.length; i++) {
newArray.push(callback(this[i]));
}
// Only change 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 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36.

Challenge: Implement map on a Prototype

Link to the challenge:

Hello!

But you explained it here:

Maybe if you paste the code here to see how it works may help :slight_smile:.

1 Like

here the myMap method is being executed on the s array, with the callback this time being function(item){return item * 2;}, and storing the result in new_s

1 Like

Thank you so much for that link. That will be very useful!

1 Like