Falsy Bouncer - confused by loop's behaviour

Hey all!
I’ve been working on the Falsy Bouncer Javascript challenge and am a bit confused as to what’s happening here. I’ve had a read through things and have come to a working soluton (so am happy this code does not pass the challenge), but am not sure exactly what I’ve done on one of my earlier attempts. All this does is replace everything in arr with 1s and enter 1s into arr2 despite me not actualy doing anything to arr - can anyone else see where exactly this behaviour is coming from?

function bouncer(arr) {
const arr2 = [];

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

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

      arr2.push(arr[i]);
    }
    console.log(arr2);
  } 
    console.log(arr);
  return arr2;    
}

bouncer([7, "ate", "", false, 9]);

Thanks!

Single pipes are not the same as double pipes.

You can’t string boolean tests together like that. Each test must include the thing it is being tested on. For example, if you want to check if a is either false or null:

if (a === false || a === null) {

You’ve got the exclamation point and equals sign mixed up here.

“despite me not actualy doing anything to arr”

Ahh, but you are: arr[i] =! false will set arr[i] to true since what this is really doing is:

arr[i] = !false

And then the first bitwise OR operator (with the value false) converts that to a 1, and the remaining bitwise OR operators have no effect on it due to their values being falsey. I do not claim to be an expert on bitwise operators, so my explanation perhaps lacks some details, but it’s probably close enough :slightly_smiling_face:

Bitwise operators can be a bit confusing if you don’t use them all the time (like me). But the big take away is that you want boolean ORs (double pipes) instead of bitwise ORs (single pipes).

And to be honest, you can solve this without all of these boolean expressions if you really understand falsey values in JS.

Extreme challenge: This can be solved with one pretty simple line of code.

Ok I think that makes sense, I definitely will need to read up more on falsy values!

One of the main things which was confusing me was why the loop was updating arr, almost as if the if statement condition was being exected as a command. I guess this was because of using the incorrect version of OR?

That, and because of the first thing you did in the if statement:

arr[i] = !false

This is changing the value at arr[i].

Ahh right yes I see what you mean. That makes sense now, I’ll bear that in mind and be sure to check I’ve got ! and = round the right way next time!

I will give this a go once I’ve built up my knowledge a litte more!

Thanks a lot for your explanation :slight_smile:

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