Filter method with callbacks

// the global Array
var s = [23, 65, 98, 5];

Array.prototype.myFilter = function(callback){
  var newArray = [];
  // Add your code below this line
  this.forEach(function(x) {
    if (callback(x) == true) {
      newArray.push(x);
    }
  })
  // Add your code above this line
  return newArray;

};

I am trying to figure out how callback functions work, but it does not make any sense to me, it’s like they are coming from another planet, wasn’t callback supposed to be an argument, not a function?

Functions can be arguments. Functions can be passed around like any other variable. They can go into another function as an argument or come out as a returned value.

Here you may want to use the strict equality operator ===
Because:

2 == true // is true
0 == true // false
-1 == true // true
"Hi" == true // true

// but

2 === true // false
"Hi" === true // false

Just in case someone write it wrong and your callback doesn’t return a Boolean. To avoid unwanted results.

Thanks for the help :slight_smile:

To me personally this solution would make much more sense.
// the global Array
var s = [23, 65, 98, 5];

Array.prototype.myFilter = function(callback){
var newArray = [];
// Add your code below this line
for (var i = 0; i < this.length; i++) {
if (callback(this[i]) === true) {
newArray.push(this[i]);
}
}
// Add your code above this line
return newArray;

};

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

It is a perfectly valid solution. The other one was making use of the forEach() method which does a thing totally similar to your loop, but is easier to read and write (your solution is still perfectly valid)