Extra element in Functional Programming: Implement map on a Prototype

Tell us what’s happening:
The output should be [46, 130, 196, 10] but I am also getting a NaN element after the 10. What does it mean?

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
var copy=s.slice();
for(let i=0; i<=copy.length; i++) {
newArray[i] = (callback(copy[i]))
console.log(newArray);
}
// 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.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/truncate-a-string

Hi,

I think it is because of this line:

for(let i=0; i<=copy.length; i++) 

copy.length = 4, so when i=4, copy[4] becomes undefined. That’s why you are getting NaN after 10. So the statement should be

for(let i=0; i<copy.length; i++) which accounts for all the existing indexes in the copy array

1 Like

Oh thank you it works now