Iterate Odd Numbers With a For Loop , completed but don't undestand

Here’s my code:

// Setup
const myArray = [];

for (let i = 1; i < 10; i+=2) {
  myArray.push(i);
}

// Only change code below this line

This makes myArray = [1, 3, 5, 7, 9]. My question is: Why doesn’t it equal [3, 5, 7, 9, 11]?

From looking at the code, it looks like the function is starting with i equaling 1, and then checking to see if i is still less than 10, and then adding 2 to it, AND THEN pushing it into the array. Is the push happening before the i += 2? Also, when i = 9, it is still below 10, and therefore would have 2 added onto it and be pushed into myArray right?

Your browser information:

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

Challenge: Basic JavaScript - Iterate Odd Numbers With a For Loop

Link to the challenge:

I think you have a little misunderstanding of the order in which a for loop works.

Lets look a little more closely

for (INITALIZE; CONDITION; INCREMENTOR) {
  BODY;
}

Here is the order of operations

  1. INITALIZE any variables specified in the loop head

  2. Check the CONDITION. If the condition is false, you’re done.

  3. Run the BODY of the loop.

  4. Run the INCREMENTOR to update the index variable(s). Go to Step 2.

1 Like

This is a great explanation! Thank you!

1 Like

You are iterating through the array [1,2,3,4,5,6,7,8,9] to output odd numbers only. Given the condition i += 2, or i = i+2, the first value after iteration is 1, the next value is 1+2 = 3, the next is 3+2 = 5, next value is 5+2=7, and finaly 7+2=9.The execution is halted once you get to 9 because 11 would be greater than 10 which would violate the incrementor rule i.e i<10.

Hope this also helps

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