Where is NaN coming from?

Tell us what’s happening:
The console.log at the in the code below displays:
46 130 196 10 NaN
If there are only 4 items in the array, why does it console.log the 5 items, specifically the NaN?

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 in s) {

    console.log(callback(s[i]));

    newArray.push(callback(s[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/81.0.4044.138 Safari/537.36.

Challenge: Implement map on a Prototype

Link to the challenge:

@Catalactics I understand that NaN is not a number, but when there are only 4 items in the array why does the for statement display a 5th item (NaN)?

Sorry, looking back at it I don’t think I explained my question very clearly

try adding a console.log(i, s[i])
the for in loop is not recommended for arrays

2 Likes

Is there an easy explanation on what that extra iteration is?

console.log(i, s[i], callback(s[i]))
0 23 46
1 65 130
2 98 196
3 5 10
myMap [Function] NaN

the for in loop is also iterating over the properties in the prototype, as far as the documentation can tell me

the for…in loop should not be used on arrays for this reason, unexpected results
the for…of loop is a better choice, or any of the other loops taught in the curriculum

2 Likes

Thank you all! Your comments about arrays and for loops are very helpful