Challenge Bonfire: Falsy Bouncer has an issue.
User Agent is: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36
.
The instructions to Falsy Bouncer indicate that a Falsy value is of various types including NaN.
The first test requires that the function call bouncer([7, "ate", "", false, 9]) should return [7, "ate", 9]
however note that the string "ate" is NaN therefor it should not be included in the resulting array.
Therefor it seems that there is no way to pass test 1 and test 3 with the same code block, they are mutually exclusive answers.
My code:
function bouncer(arr) {
arr = arr.filter(function(val){
if (val === false || val === null || val === undefined || val === "" || val === 0 || isNaN(val)) return false;
return true;
});
return arr;
}
bouncer([false, null, 0, NaN, undefined, ""]);
Apologies in advance if I have misunderstood something here.
NaN
is an actual value a variable can have and it is falsey. "ate"
is not a number and isNan("ate")
will return true, but the value "ate"
is not falsey, only the specific value of NaN
is falsey. The beauty (and occasional bug source) of falsey values is that you don't need to explicitly look for them like your code does, because whenever a boolean value is needed Javascript will type coerce them to a boolean value of false. What this means is that the code for your filter function can simply be this:
arr = arr.filter(function(val){
return val;
});
Thanks and happy coding!
And, technically, you can use the Boolean
function to do that for you, so the problem can be solved:
return arr.filter(Boolean)
, since Boolean takes truthy/falsy values and returns true or false.
Most helpful comment
And, technically, you can use the
Boolean
function to do that for you, so the problem can be solved:return arr.filter(Boolean)
, since Boolean takes truthy/falsy values and returns true or false.