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: