Why i should use 'length' in this function of map?

Array.prototype.myMap = function(callback) {
  const newArray = [];

  for (let i = 0; i < this.length; i++) {
    newArray.push(callback(this[i]));
  }

  return newArray;
};

i can’t figured out cuz i should use length, i just know that length return the number of index in the console.

Do you understand what this represents in this function?

The array.prototype.myMap , if i’m right

I mean is the number write as a item in the console

No, this represents the array that the myMap method will be called on.

function timesTwo(elem) {
  return elem * 2;
}

const arr = [ 1, 2, 3, 4, 5];
const anotherArr = arr.myMap(timesTwo); // `this` is `arr` while inside the `myMap` method
console.log(anotherArr); // displays [ 2, 4, 6, 8, 10]

Since this is just the array the method is called on and you need to iterate over the entire array with your for loop, you use i < this.length as the for loop conditional.

1 Like

Ok, i get it, thank you for clarify this topic. You’re the best