Falsy Bouncers Not working

Falsy Bouncers Not working
0

#1

Good day fellow campers, in my code below i wonder why the NaN is part of my return
please what could be wrong with my code?

Your code so far


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

}

bouncer([1, null, NaN, 2, undefined])

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/falsy-bouncer


#2

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
}

#3

NaN is a weird one. You can’t compare it to NaN.

What you want is something like this instead:

if (arr[i]) {
correctValue.push(arr[i]);
}

Because then the if statement will only evaluate to true if the value of arr[i] is a ‘truthy’. All falsy values (like NaN) will evaluate to false.

if you really want to check if something is NaN use the isNaN method described here:


#4

When arr[i] is ‘NaN’, you have:

NaN !== NaN // evaluates to true

so NaN gets pushed to the correctValue array.


#5

Thanks for your comments and corrections. i figured out the error. in my if statement i should just put…arr[i] in place of arr[i] !===NaN


#6

Yes and no. If you try the if statement I mentioned earlier it will help you understand how simple this exercise really is.


#7

You can use push for this challenge, but filter is perfect for this kind of thing. Bear in mind that the filter function simply tests for the truthiness of whatever’s returned for each element (so arr.filter(el => 1) returns the original array unchanged, and arr.filter(el => 0) returns an empty array).