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:-

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

  // Only change code below this line

  // Only change code above this line
  return newArray;


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


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, 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. 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.


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

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