Functional Programming : forEach - filter implementation

Why this is used with forEach in the code below? And what the line “Array.prototype.myFilter = function(callback)” means ? Please explain.

Question link:-https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/functional-programming/implement-the-filter-method-on-a-prototype

// The global variable
var s = [23, 65, 98, 5];
 var newArray = [];
  Array.prototype.myFilter = function(callback){

  // Only change code below this line

this.forEach(function(x){
  if(callback(x)==true)
  {
    newArray.push(x);
  
  }
});
  // Only change code above this line
  return newArray;

};

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

console.log(new_s);
console.log(s);
console.log(newArray);

Hi there
So I could find the following information for you:
The answers aren’t mine but, they will help you understand more :3

The argument to filter is a function called callback that is applied to each argument of the array

So callback(item) is literally just calling that function

If I type in

a = 3

in a repl.it, it will return “3” because it is evaluating what I have there.

If I do:

Array.prototype.myFilter = function(callback) { }

It returns back a function. repl.it doesn’t list the whole function so it just tells you what it is. It is one of the oddities of command line JS. Don’t worry about it

Implement the filter Method on a Prototype explain.

1 Like

it is little confusing I am still unable to understand why this is used instead of array name before forEach?

because you need the myFilter method to be reusable.
And this reference the method on which the array is called

in this particular case, this is the s array, but you need it to work on any array

you also can’t have it to push on the newArray array, when this is defined outside the method, one, because it doesn’t respect the Only change code below this line, and two because… (explanation below)

Your code contains global variables that are changed each time the function is run. This means that after each test completes, subsequent tests start with the previous value. To fix this, make sure your function doesn’t change any global variables, and declare/assign variables within the function if they need to be changed.

Example:

var myGlobal = [1];
function returnGlobal(arg) {
  myGlobal.push(arg);
  return myGlobal;
} // unreliable - array gets longer each time the function is run

function returnLocal(arg) {
  var myLocal = [1];
  myLocal.push(arg);
  return myLocal;
} // reliable - always returns an array of length 2