Why is this not working (Falsy bouncer)

Tell us what’s happening:
I don’t see why this is not working. I used a for-lus to iterate the array. In the for-lus there’s a if-lus to see if the current arr[i] is equal to a falsy value. If that is the case than it deletes it + it resets the “i”.

The first test works, but the 2 others not. Can someone help me?

  **Your code so far**

function bouncer(arr) {

for(let i = 0; i < arr.length; i++){

   if(arr[i] == false || arr[i] == null || arr[i] == "" || 
   arr[i] == 0 || arr[i] == undefined || arr[i] == NaN ){

     arr.splice(i,1);
      i = 0;
   }
}

console.log(arr);
return arr;
}

bouncer([7, "ate", "", false, 9]);  // [ 7, 'ate', 9 ]
bouncer([false, null, 0, NaN, undefined, ""]); // [ null, NaN ]
bouncer([null, NaN, 1, 2, undefined]); // [ NaN, 1, 2 ]



  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.60 Safari/537.36

Challenge: Falsy Bouncer

Link to the challenge:

When you do the arr.splice(i,1) you are changing the number of elements in your array and thus the position also changes. Better declare an empty array and push it or use high order function without the need for a for...loop like filter function.

No, then you change it to a string right? I just tried it out, but as expected it is still not working :cold_sweat:

Sorry I changed my answer. Check it out.

There is a bug also in JS that NaN is not actually equal to NaN. Comparing to one value the work around is using isNaN() function. However for multiple values like this problem, it would not work. A good work around is using includes method in an array. Like someArray['a','b','c'].includes('d') which in this case would return false. And that you have to find out yourself.

See MDN source here.

You can’t really compare all falsy values like that.

The point of this challenge is to use the idea of fasliness.

if (some truthy value) {
  // this block executes just like if the condition was literally 'true'
}
1 Like

To be clear, it’s a good thing that Nan isn’t Nan in JS. That’s intentional.

I don’t really like that this works. It isn’t a great approach to this problem in any case.

I agree that it’s a bad idea t splice out values as you iterate over an array.

2 Likes

@JeremyLT @edper Thank you for your time to help :wink:
I can move now to the next exercise! :raised_hands: :raised_hands:

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.