Explain Implement map on a Prototype

Explain Implement map on a Prototype
0
#1

Tell us what’s happening:
what else am i doing wrong here ? please also explain why

for (let i = 0; i < callback.length; i++) {
newArray.push(callback[i]);
}
or a simple spread operator var newArray = […callback]
wont work in this challenge. Thanks.
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 < this.length; i++) {
    newArray.push(this[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 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36.

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

1 Like
#2

You are not using the callback inside to transform each element of the array which myMap is called on. You should be pushing the result of calling the callback function on each element.

1 Like
#3

thanks for the timely reply Mr Randel.

#4

The function myMap takes one argument, which has been called callback. It’s a function, which is why neither of those things will work: you cannot loop over a function, and a function is not something you can spread.

And you use myMap like [1,2,3].myMap(doSomething).

this, in the prototype function you are writing, is the thing to the left of the dot when you call the function. So in the above, the thing to the left of the dot is [1,2,3]

1 Like