Falsy Bouncer - Trying to complete an alt objective to learn

This challenge asks us to remove any falsy element from the array.

I’m getting to that but first I want to achieve the following:

Remove any non-boolean elements from the array.

The code below was made to do this but for some weird reason the final console.log(arr) gives the following as output

ate,false

surely ‘‘ate’’ is not of the boolean type hence during this check should be removed too??

The console.log showing every iteration is:

7,ate,,false,9
ate,,false,9
ate,false,9
ate,false

so, any non boolean elements like 7 , ’ ’ (empty string) and 9 are removed but for the life of me I am struggling to see why ‘‘ate’’ is so special such that it is still in the array at the end?

Your code so far






function bouncer(arr) {
  
  for (var row = 0; row<arr.length ; row++) {

console.log(arr);

if ( typeof (arr[row])  !== 'boolean') {
arr.splice(row,1);
}



  }

  console.log(arr);

  return arr;


}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36.

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

The error you are seeing has nothing to do with the fact that it’s the string “ate”. The problem comes from the fact that you are mutating the array as you’re iterating over it. On your first pass of the for loop (row is 0), it removes the first element of the array. That means that the index of "ate" is 0. But 0 has already been checked, so "ate" is skipped.

If you only want to keep elements that are the boolean value true, you could just do (arr[row] === true).

Ah I see

Why and when is this occuring?

The for loop starts at index 0 so as far as I understand the following happens:

First iteration:

arr[0] = 7

if ( 7 is boolean? )

No, therefore arr[0] removed

arr is now [’‘ate’’ , ‘’ ‘’ , false , 9]

Iteration 2:

arr[1] = ‘’ ‘’;

Ah, now I answered my own question :no_mouth:

Okay so trying ===truw

if ( arr[row]  == true) {
continue;
}
 else {
  arr.splice(row,1);
}

Is how I’m using splice incorrect?

I just want to point out that what you did here is an EXTREMELY IMPORTANT debugging technique. When you’re error-checking a function, grab a pen and paper and do this exact thing.

.filter is the way what a useful function

function removeFalsy (x) {
if (x) {
  return x;
}
}

function bouncer(arr) {
  
  let arrNoFalsy = arr.filter(removeFalsy);

  return arrNoFalsy;
}