What am I doing wrong while using splice method?

Why is my code skipping alternate elements, when using (.splice) method?

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

bouncer([false, null, 0, NaN, undefined, ""]);

Challenge: Falsy Bouncer

Link to the challenge:

Because you’re mutating the array as you remove items from it.

Let’s say you remove the item at [i], now the item that was just at [i + 1] is now at [i]. But then the loop goes to the next iteration. Hence, that items gets skipped.

1 Like
1 Like

yes, thank you for the detailed explanation, i saw the hints and they mentioned filter and push methods. I wanted to try out splice as i had just learnt it in the previous challenge. But my logic was not correct

I guess you could use splice if you compensate for it by also updating i when you remove a value.

I don’t think it would be very easy to understand that sort of code though.

yeah would like to see how that will work, currently i am unable to formulate how to update “i” value in same “for” loop

i is a variable like any other. You can assign to it with =.

for (let i = 0; i < arr.length; i++) {
  i = 200;

lol, just tried “i–” after “arr.splice(i,1)” and it works, thank you!

1 Like

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