Falsy Bouncer - Issue with NaN

NaN is not being removed from the lists like I expected. Can anyone explain to me why this is? Here’s my code:

function bouncer(arr) {
  // Don't show a false ID to this bouncer.
  let container = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] !== false && arr[i] !== null && arr[i] !== 0 && arr[i] !== "" && arr[i] !== undefined && arr[i] !== NaN) {
    container.push(arr[i]);   
    }
  }
  console.log(container);
  return container;
}

bouncer([1, null, NaN, 2, undefined]) // Returns [1,NaN,2] instead of [1,2]
bouncer([false, null, 0, NaN, undefined, ""]) // Returns [NaN] instead of []

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
}

Is there a way to test for NaN’s existence besides arr.filter(Boolean)?

.filter(Boolean) is not the only way to use the falsiness of a value.

There is a function, for when you need to specifically check whether something returned NaN.

Thanks. This is great.

You don’t need to use the Boolean function with filter: and both of these are the same:

Boolean(arr[i])
!!arr[i]

If in a conditional, anything in the if block is converted to true/false:

if (arr[i])

filter does this as well (so just return the value in the function, the result will be converted to true/false:

arr.filter(value => value)

NaN is not equal to anything else including NaN:

arr[i] !== arr[i]

To test if a value is NaN:

Number.isNaN(arr[i])
1 Like