Implement map on a Prototype, correct method?

Tell us what’s happening:
So my code passes but I can’t help but feel I’ve done it wrong as I’m accessing the global array “s” and thus my solution isn’t a pure function. Can anyone tell me how to access the array properly in this context?

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 < s.length; i++) {
    newArray.push(callback(s[i]));
  }
  // Add your code above this line
  return newArray;

};

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

console.log(new_s);

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

Using the key word this inside the function would refer to the array on which the myMap method is called. Replace s with this.

This will allow your method to be called on any array directly like:

var result = [23, 65, 98, 5].myMap(function(item){
  return item * 2;
});

console.log(result) // displays [ 46, 130, 196, 10 ]
1 Like

Great, thank you very much.