What's the role of THIS in this filter method?

I am new to this outside of constructors, what role does it play here ?

// The global variable
const s = [23, 65, 98, 5];

Array.prototype.myFilter = function(callback) {
  // Only change code below this line
  const newArray = [];
  for (let i = 0; i < this.length; i++) {
    callback(this[i]) ? newArray.push(this[i]) : []
  }
  // Only change code above this line
  return newArray;
};

const new_s = s.myFilter(function(item) {
  return item % 2 === 1;
});
  }```

When you’re defining a new prototype method, it’s the same general concept as creating a method in an object constructor. this works the same way: referring to whatever array the method is being called on.

1 Like