Https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/falsy-bouncer

Hi, I need help with this challenge. I don´t understand why when i test this code doesn´t remove the values null, NaN y "". I think it might be because of the splice() that I’m using it wrong.


function bouncer(arr) {
for (let i = 0; i < arr.length; i++) {
  switch (arr[i]) {
    case false:
    case null:
    case undefined:
    case 0:
    case "":
    case NaN:
      arr.splice(i,1);
      //break;
  }
}
console.log(arr);
return arr;
}

bouncer([false, null, 0, NaN, undefined, ""]);

Challenge: Falsy Bouncer

Link to the challenge:

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
}
1 Like

Hi and welcome to the forum!

Your problem is here

You can’t check if a value is NaN because NaN === NaN is always false.

You need to instead use the idea of falsyness to pass this challenge.

The hint says:

Hint: Try converting each value to a Boolean.

I’d try seeing what happens if you try

let myVar = 0;
if (myVar) {
  console.log("This is Truthy");
} else {
  console.log("This is Falsy");
}
1 Like

Thank you both! I think I understand now :slight_smile:

1 Like