Falsy Bouncer - My code works but I'm not sure why

Falsy Bouncer - My code works but I'm not sure why
0

#1

Hi everybody!
My code for solving the “Falsy Bouncer” challenge works but I’m actually not sure how…
One of the requirements for the challenge is that the function will filter the “NaN” items from the array, and I didn’t do anything about it and it still works. Does anyone know how and why?

Here is the challenge:

Remove all falsy values from an array.
Falsy values in JavaScript are false, null, 0, “”, undefined, and NaN.

And here is my code:

function filtered(value) {
if((value !== null) && (value !=="") && (value !== 0) && (value !== false) && (value !== undefined)) {
return value;
}
}
function bouncer(arr) {
var newArr;
newArr = arr.filter(filtered);
return newArr;
}
bouncer([1, null, NaN, 2, undefined]);

Thanks!
Vered


#2

Your code will work even without if statement.

The way .filter() works is it checks the value returned from callback (in your case filtered() function) and if it’s Truthy the value gets returned from .filter().

So in your code NaN passes the if, but gets filtered in .filter();


#3

Thanks for your answer! So If I understand correctly .filter() filters NaN automatically?


#4

Yes, NaN and all other falsy values.


#5

Oh, great. Thank you! :slight_smile: