Falsy Bouncer check solution

code is right in this way but

Your code so far


function bouncer(arr) {
  // Don't show a false ID to this bouncer.
 let narr=[];
  for(let i in arr)
 {
   if(arr[i])
   {
        narr.push(arr[i]);
   }
 }
  return narr;
}
console.clear();
console.log(bouncer([7, "ate", "", false, 9]));

when i write it like this there is some problem


function bouncer(arr) {
  // Don't show a false ID to this bouncer.
  for(let i in arr)
 {
   if(!arr[i])
   {
        arr.splice(i,1);
   }
 }
  return arr;
}
console.clear();
console.log(bouncer([7, "ate", "", false, 9]));

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/falsy-bouncer

If I’m not mistaken, it’s because in the second case (the one that doesn’t work), you are mutating the array that you are iterating through. So during the third loop (when i is 2) where arr[i] is "" and is falsy, the if block gets triggered and the arr gets spliced.

So after the third loop, arr become [7, "ate", false, 9]; since you have already looped through the third position and that arr got shortened, the next value arr[3]is now 9 instead of false, and therefore the array returned includes false (which is not what you want).

Try console.log(i, arr[i]) just outside of the if block—you will see that the loop only runs 4 times. :slight_smile: I hope that helps!

2 Likes

awesome thanks :slight_smile:

1 Like