Code isn't working!

Tell us what’s happening:
I don’t know what’s wrong in this code. It has thrown an error.
Thanks for any help !

Your code so far


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

Array.prototype.myFilter = function(callback){
// Only change code below this line
var newArray = callback.filter(item => item % 2 === 1);
// Only change code above this line
return newArray;

};

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36.

Challenge: Implement the filter Method on a Prototype

Link to the challenge:

Hello there,

The filter method (Array.prototype.filter) is exactly that - a method available for use on arrays.

callback is a function. Hence the error:

TypeError: callback.filter is not a function

Think about how you are using the method:

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

It is a method, not a function:

const myArray = [1, 2, 3, 4];

// How to use a function
myFunction(myArray);
// How to use a method
myArray.myMethod(myCallbackFunction);

Obviously, the above code will not do anything, but you can see the difference between calling a function, and passing an argument to the function, and using a method on an object, and passing a callback function to the method.

Hope this clarifies.

How can i use the “callback” argument inside the function ?

Remember, you are not creating a function, you are defining a method. callback is a function. In this case, it just-so-happens to accept one argument:

function(item){
return item % 2 === 1;
}

So, when you use callback you need to pass it one argument, and it will return something you can use.

1 Like

I assume you did a very similar thing in the challenge two prior?:

I really get stuck in this challenge because I don’t know exactly how to use the argument “callback” .

Okay thank you !
I’ve just undertood what do you mean.