Shouldn't the variable pass through the condition in a "for" loop?

Tell us what’s happening:

Your code so far


// Setup
var myArray = [];

// Only change code below this line
for(var i = 1; i < 10; i += 2) {
myArray.push(i)
}

console.log(myArray)

The lesson showed an example of a “for” loop:

var ourArray = [];
for (var i = 0; i < 10; i += 2) {
  ourArray.push(i);
}

But when I replicate the exact same code it and console.log it, it shows [ 0, 2, 4, 6, 8 ].
My question is: shouldn’t 8 pass through the condition then become 10 since 8 is less than 10?

Your browser information:

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

Challenge: Iterate Odd Numbers With a For Loop

Link to the challenge:

I’m confused by your question. 8 is less than 10, so it gets pushed onto ourArray.

Loop execution has 3 stages

  1. Check exit condition
  2. Execute loop body
  3. Increment loop iterator

When i == 8, the exit condition has not been met, so the loop body executes and then the iterator increments to i == 10, which causes the exit condition to trigger.

Yes, but shouldn’t 8 get passed to the final-expression to += 2 to become 10

It does. It gets added to the array, then increments by 2, then the loop exits.

so after the condition has been met it checks again to see if it triggers the exit condition?

so it checks again if it matches the condition, right?

It checks at the start of every iteration. After i becomes 10, that check is false, so the loop exits and 10 is not added to the array.

The three steps are always in that order.

  1. Check exit condition
  2. Execute loop body
  3. Increment loop iterator

For this function

  1. loop initializes, i == 0
  2. iteration 0
    a) check exit condition, i < 10 :heavy_check_mark:
    b) execute loop body, push 0 onto the array
    c) increment loop iterator, i == 2
  3. iteration 1
    a) check exit condition, i < 10 :heavy_check_mark:
    b) execute loop body, push 2 onto the array
    c) increment loop iterator, i == 4
  4. iteration 2
    a) check exit condition, i < 10 :heavy_check_mark:
    b) execute loop body, push 6 onto the array
    c) increment loop iterator, i == 8
  5. iteration 3
    a) check exit condition, i < 10 :heavy_check_mark:
    b) execute loop body, push 8 onto the array
    c) increment loop iterator, i == 10
  6. iteration 4
    a) check exit condition, i < 10 :heavy_multiplication_x:
  7. execution halts and loop is finished
1 Like

oooohhh i get it now xD thanks mate!!

1 Like

I get it now, Thank you so much!!