It’s just a function. You can pass functions around the same as any other value in JS. They only execute if you call them (someFuntion
vs someFunction()
), so you’re just passing a reference to the function. So you can call it whatever you want when you define myFilter
, the same as any other argument. It’s just normally called what it is generally known as, a callback
(cb
, fn
, fun
are other common names)
With myFilter
, you want be able to pass a function to it. That function needs to take a single argument, and return true or false. Then you loop over your array and run the function for each element, pushing all the values that return true
into a new array, which you return.
So you don’t need to know what that function is in advance, just that it takes a single value and returns true or false - it could be:
function greaterThan2 (x) { return x > 2; }
or
function notA (x) { return x !== 'a'; }
So then you can do
[1,2,3,4].myFilter(greaterThan2) // returns [3,4]
['a', 'b', 'c'].myFIlter(notA) // returns ['b', 'c']
Or you can pass the callback function right in, same thing:
[1,2,3,4].myFilter(function greaterThan2 (x) { return x > 2; })
Or more tersely (again, exact same thing):
[1,2,3,4].myFIlter(x => x > 2);
That function is just a parameter of the myFilter
function, and you can call parameters anything you like