Falsy Bouncer - my own code

Falsy Bouncer - my own code
0.0 0

#1

I have read the solution and I totally get it. Although I never would have reached that solution on my own in a million years.

I would like to finish the code that I started just so I know that I can at least make it work. Can someone please review my code? And answer this question:

1 - Why is
console.log(arr[i]);
returning only the truthy elements but
arr1.push(arr[i]);
builds an array with ALL elements of arr?

Thank you.

Your code so far

function bouncer(arr) {
  // Don't show a false ID to this bouncer.
  
  //Build an array of just falsy values
//   var arr1 = [false, null, 0, "", undefined, NaN];
  var arr1 = [];
  
  //Go through test array to see if any elements match falsy values
  for (i=0; i<arr.length; i++){
    if (arr[i] == false) {
      //do nothing
    }else 
      console.log(arr[i]);
      arr1.push(arr[i]);
  }
  console.log(arr1);
//   return arr1;
}


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

Your browser information:

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

Link to the challenge:


#2

Because your else does not have { } surround both lines of code. If an if or else statement does not have { } then only the first statement following (in this case console.log(arr[i])) gets executed as part of the else code block. The arr1.push(arr[i]); will get executed, because it is not part of the if or else block of code. It is as if you wrote like:

    if (arr[i] == false) {
      //do nothing
    }else {
      console.log(arr[i]);
    }
    arr1.push(arr[i]);

BTW - your if statement is not testing for falsy values. It is only testing for the value false. false is one of the 6 possible falsy values. The other ones are null, 0, “”, undefined, and NaN