return (a % 2 == 0) in a filtering functions means?

I’m doing this tutorial by kirupa:

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

even_numbers = numbers.filter(fxn);

function fxn(a) {

return (a % 2 == 0);

}

console.log(even_numbers);

In this code we return (a%2==0). IMO, it returns true or false but not a. isn’t it? How does that work? I’m not getting. Does that mean this?

if(a%2==0)

{

return a;

}

What we are doing with that line is checking if the number is even or odd by seeing what the remainder is when we divide by 2.

The result of that is true if the remainder is 0, and false if the remainder is something else.

What we are returning with that function is a true or false for each number. We don’t return the value of a.

:nerd_face:

but it outputs numbers, how?

That function gets called at each number. If the result is true, the number stays. If the result is false, the number is skipped.

Isn’t this a weird syntax? So that basically means return a if (a condition true)? right? is this specific to filter function that I’ve not read about?

No you can evaluate anything truthy or falsey with an if, ternary, switch/ case , while, for, nullish coalescing…. :slightly_smiling_face:

1 Like