Confusion about this if..else

Hello there, I am a beginner in javascript.

I am trying to run this fuction with splice(). But the way the code runs confuses me.

The arr should return [7, ‘ate’ , 9], ( “” and false ) should be removed by the function, but its returning [7, “ate”, false, 9]. In test2 I put false in the condition spot, and false is returned. So why doesn’t it run the arr.splice(i, 1) line when arr[i] = false ??

ps. I saw the solution in the help page. I am just wondering what went wrong.

Thanks
Your code so far


function bouncer(arr) {
for (let i=0; i < arr.length; i++) {
  if (arr[i]) {

  } else {

    arr.splice(i, 1);
  }
}
console.log(arr);
return arr;
}
bouncer([7, "ate", "", false, 9]);



//test2
if (false) {
console.log(true);
} else {
console.log(false);
}
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36 OPR/77.0.4054.172

Challenge: Falsy Bouncer

Link to the challenge:

You should not modify an array as you iterate over it. That always is messy. In this case, you end up changing the length of the array and reindexing the elements after the one you remove.

1 Like

Thanks for pointing it out Jeremy.

1 Like

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