I am working through the basic algorithm scripting and have hit an odd snag with ‘falsy bouncer’.
I chose to do this by using arr.filter(fn) - there are other ways but I wanted to do this. So I created my function filter(n) and this is it:
function filter(n) {
if (n === false || n === null || n === 0 || n === "" || n === undefined || n === NaN){
return false
}else{
return true
}
}
I also created the main function which calls this. I haven’t included it because it works perfectly and I don’t want to spoil things for you.
My problem is this…
filter(n) works perfectly, returning false for false, null, 0, “”, and undefined, correctly returning false and true for anything else. But, it returns true for NaN. I have tried putting NaN in as a string, as a list, as an object, I’ve put it in its own if statement, but whatever I do it steadfastly returns true. And I notice that in the code here it is being treated differently to all the others. I’m stuck on this one and could do with a bit of a pointer if one is available.
I have managed to solve this with a considerable amount of reading around the subject. I now know there are much simpler ways of doing this, but I solved it with the code I wrote - that is my level in javaScript - some of the less code intense versions of the solution (like 4 lines of code) leave me not understanding how they actually work.
For anyone who needs to know I used !!n === !!false etc - yes, the double negative works with NaN.
Thanks Tzerio, this idea of truthy and falsy is a little odd to me but I know where to go to get the information and I guess I will keep trying until I really understand it.