Implement map on a Prototype for and forEach methods working for in method weird

Tell us what’s happening:
Ok so i manged 2 do this with a for loop and i manged with a bit more effort than i would of liked to do it with arrow functions + forEach however my for in loop does not work
Your code so far

this.forEach((i) => newArray.push(callback(i))) (working arrow function forEach)
for (let i = 0 ; i < this.length ; i++){                  (working forLoop method)
newArray.push(callback(this[i]))
newArray[i] = callback(this[i])
console.log(newArray);
 for ( let i in this){                                            //for in loop returns 46,130,196,10,NaN WHY?
    
newArray.push(callback(this[i]))
newArray[i] = callback(this[i])
console.log(newArray);
 }

why does it return an extra value of NaN i thought for in loops stoped at the end of the array


**Your browser information:**

User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0`.

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

For…in is for traversing object keys, not array values. An array is an object, so it kinda works, but an array looks like this:

[10,20,30]
// Same as
{0: 10, 1: 20, 2: 30, length: 3}

The second representation is what you would be traversing. for…in isn’t terribly useful anyway, and definitely shouldn’t be used for arrays

1 Like

ah-ha right so abit like how in C strings dont exist in javascript arrays dont exist they are actually objects so im getting an additional value of length however why does it not just come up with the length value and it comes up with NaN?

On the last itteration i === "myMap"

Try wrapping the array manipulations in an if with hasOwnProperty

for (let i in this) {
  if (this.hasOwnProperty(i)) {
  newArray.push(callback(this[i]))
  newArray[i] = callback(this[i])
  console.log(newArray);
  }
}

For array looping, you may want to use for..of instead.

Yep, sort of. JS only has one collection type (objects), every other data structure is built from them. Arrays have a few extra things built into them so it’s not quite as simple as my example, there are other properties so it was kinda a simplification what I said (as @lasjorg showed).

For…in loops have specific uses, but they aren’t normally a general tool that you reach for, seconding use for…of loops to go through iterable data structures like arrays.