Why doesn't my solution work? - Basic Algorithm Scripting - Falsy Bouncer

This is my first pass at this challenge and I’ve got some other ideas for solving it, but I’m wondering why my code doesn’t fulfill the requirements. It looks as though my push is ignoring my if statement. Seems to me it should only be pushing the correct values into my new array but it’s pushing everything in. I’m obviously using the wrong approach, but could someone help me understand why this isn’t working? Thanks!

function bouncer(arr) {
  const newArray = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] !== false || arr[i] !== null || arr[i] !== 0 || arr[i] !== "" || arr[i] !== undefined || arr[i] !== NaN) {
      newArray.push(arr[i]);
    }
  }
  return newArray;  
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36

Challenge: Basic Algorithm Scripting - Falsy Bouncer

Link to the challenge:

That makes sense. Thanks! It feels like it was years ago since I went through that challenge, though it’s probably only been a week or two.

I was able to figure out a way but had to do a google search to figure out what to do with NaN. That was real tricky.


function bouncer(arr) {
  const newArray = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] !== false && arr[i] !== null && arr[i] !== 0 && arr[i] !== "" && arr[i] !== undefined && Boolean(arr[i]) === true) {
      newArray.push(arr[i]);
    }
  }
  return newArray;  
}

I know, I have to do major refinements to the way I write as I usually have tons more lines of code than the solutions provided. I always check the solutions after I finish mine and see how inefficient my code is. That said, 4 days ago I literally was just staring at the computer screen wondering how I was supposed to know how to solve any of these, and then something in my brain clicked (thank God). I’ll probably come back after I finish the entire Javascript certification and redo these with a focus on minimizing my code.

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