For loop skips an iteration

Tell us what’s happening:
for the given test statement; it is clear that the index 4 of value false is skipped for no known reason.

Your code so far


function bouncer(arr) {
  for (const ind in arr) {
    console.log(`!arr[${ind}]: ${!arr[ind]} of value: ${arr[ind]}`);
    if (!arr[ind]) {
      arr.splice(ind, 1);
    }
  }
  console.log("arr: " + arr);
  return arr;
}

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

Output

!arr[0]: false of value: 7
!arr[1]: false of value: ate
!arr[2]: true of value: 
!arr[3]: false of value: 9
arr: 7,ate,false,9

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36.

Challenge: Falsy Bouncer

Link to the challenge:

Probably because the array is being mutated?

It’s a matter of checking how splice works. If it mutates, then :

//this
[7, "ate", "", false, 9]
0,    1,   [2,]   3,   4
//Becomes
[7, "ate",false, 9]
0,     1     2     3

The ind passes from our position [2] to 3.
But now 3 corresponds to 9.

1 Like

So how to come around it? I mean i understand the problem and the only solution i got is to change this synthesized for loop into regular one.

I’m not sure what this particular exercise was about. I could give you a way to prove my previous claim though, and for you to practice:

function bouncer(arr) {
  var counter = 0
  for (const ind in arr) {
    console.log(`!arr[${ind-counter}]: ${!arr[ind-counter]} of value: ${arr[ind-counter]}`);
    if (!arr[ind]) {
      arr.splice(ind, 1);
      counter+=1
    }
  }
  console.log("arr: " + arr);
  return arr;
}

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

Maybe someone else can help further!

1 Like

don’t use splice on the array you are iterating over. You can solve this in other ways without changing the function parameter

2 Likes