Implement map on a Prototype: With for/in loop

Tell us what’s happening:

I’m trying to use a for/in loop to complete this challenge but I’m getting a NaN at the end of my new_s array. Any ideas? How do I avoid myMap function in s?

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 x in s) {
  // Add your code above this line
  return newArray;


var new_s = s.myMap(function(item){
  return item * 2;
console.log(new_s) // result: [46, 130, 196, 10, NaN]

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36.

Link to the challenge:

  1. Firstly, the global array is there so you can check your code works. So if you use that global array in your solution, how, for example, could this possibly work: [1, 2, 3, 4].myMap(function(item) { return item * 2 })? It should work, but using the code you’ve written, it’ll just blow up, because firstly you’re hard-coding return values. And secondly, s only exists here, if you try to use your map function anywhere else, s doesn’t exist at all.
  2. loops are for plain objects, and have to be used with care even there. They are not for iterating over arrays. The reason the function fails is that you’ve added a property called myMap to the array. So the function tries to run n * 2 on 23, 65, 98, 5, and myMap. myMap is not a thing that can be multiplied by 2, so the end result is [ 46, 130, 196, 10, NaN ]. This is why it says in the description to use for loop or forEach, you should not be using
1 Like

Thank you for your reply, i’ll keep trying.