You need to use isNaN when checking for NaN because of the weird behaviour of NaN; e.g. NaN === NaN evaluates to false… like what… just madness. Check out this mdn article for more info.
Oddly enough, isNaN also has it’s quirks because when used directly it actually tries to coerce the value to a number; so when you pass in a non numerical string, e.g. “a”, it tries to coerce it, Number(“a”) which returns NaN, so isNaN(“a”) returns true… again, just what…
To get isNaN to truly work as expected, you can access the method directly on the Number object, where it doesn’t try to coerce the value. So your final output would look like this:
// We use ! to indicate that we don't want the value to be NaN
if ( arr[i] !== false && arr[i] !== null && arr[i] !== 0 && arr[i] !== "" && arr[i] !== undefined && !Number.isNaN(arr[i])) {
newArr.push(arr[i]);
}
One thing to note, what your actually doing is asking it to check ALL the falsy values, if you look at the boolean object and filter link in the challenge, you might find an easier way to complete this challenge
I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.
This is a common misunderstanding with the Falsy Bouncer. You can make a solution for this challenge which tests against a hardcoded list of falsy values, but it misses the point of the exercise. The concept of values being “falsy” isn’t something made up by Free Code Camp for the purposes of this challenge, but rather a quality that values have in programming languages. A value is falsy if the language treats the value as false when it is evaluated as a boolean. This means that Boolean(someFalsyValue) is false but also that we can use it in a conditional like if (someFalsyValue). We can also talk about values being “truthy”. As I’m sure you’ve guessed, truthy values evaluate to true in a boolean of logical context.
if (someFalsyValue) {
// this code block is not entered
}
else if (someTruthyValue) {
// this code block is entered and executed
}
Maybe I’m confused, but itsn’t this exactly what is expected? “a” is a string and not a number, so isNaN("a") is true. In words: “It is true that ‘a’ is not a number.” A typical use case IMO would be something like the following:
function addNumbers(a, b) {
if (isNaN(a) || isNaN(b)) {
return undefined;
}
return a+b;
}
console.log(addNumbers("a",2));
I always saw it as a way to check for NaN literally like when you’d check for most other type using typeof; which, now I think about it doesn’t really make much sense because generally speaking your only going to have a NaN value when trying to convert to a number, so the type coercion is kinda necessary in most situations, except in this specific situation where you are checking for NaN literally.