For loop with .splice()

Hi guys, doing the mini linter project and I went off on a slight tangent.

I have the following code snippet which is driving me nuts.

I understand the for loop, but I just don’t get why we start with ‘i=2’.

Wouldn’t iterating the code starting at i = 2 cut out the ‘o’ at the end, seeing as we are running over the code with 2 units increments?

Please see code:

var theArray = [‘h’, ‘e’, ‘z’, ‘l’, ‘l’, ‘l’, ‘o’]

for (var i = 2; i <= theArray.length; i += 2){
theArray.splice(i, 1);


Thanks, any thoughts appreciated.

Edit: I think i have solved this - the code I copied had the running condition at:

i <= array.length

Changing it to

i < array.length

seems to clear things up in my mind. But in this case, how come the <= array.length still produces the desired result?

The code starts with i = 2 because the first letter we want to remove is at index 2 of the array.

So inside the loop splice is removing one letter from the letter at index 2. then, the loop increments by 2, and another letter is removed at index 4.

After another increment, the ‘o’ at the end wouldn’t cut out because the loop has a condition of i <= theArray.length, and after the 2 removals theArray.length = 5 and i = 6. So the loop stops there.

Thank you sir. In the code snippet I originally posted, the stopping condition was

i <=theArray.length

Wouldn’t this mean splice() also worked on the ‘o’ at the end (whereas i < theArray.length would stop before the ‘o’)

It wouldn’t affect the ‘o’ because at that point the length of theArray is 5. so if i = 6 , its bigger than theArray.length which means we won’t enter the loop again after removing the letter at index 4.

1 Like