+- why should we use it?

Why do we have to use ±?
Shouldn’t + work to?


// Setup
var myArray = [];
for (var i = 1; i <= 9; i += 2) {
myArray.push(i);
}


// Only change code below this line
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36

Challenge: Iterate Odd Numbers With a For Loop

Link to the challenge:

You don’t use ±, that’s not a thing in programming languages.

I guess you mean +=?

So let i = 0 is what happens to kick off the loop. You initialise a variable called i, assigning it the number 0.

i <= 9 is the condition, this happens before each iteration of the loop: if it’s true, the code in the loop runs, if it’s false, the loop ends.

i += 2 is what happens at the end of every iteration of the loop.

i += 2 is shorthand for i = i + 2.

  • i is 0. Is 0 <= 9? Yes, code runs. i = 0 + 2.
  • i is 2. Is 2 <= 9? Yes, code runs. i = 2 + 2.
  • i is 4. Is 4 <= 9? Yes, code runs. i = 4 + 2.
  • i is 6. Is 6 <= 9? Yes, code runs. i = 6 + 2.
  • i is 8. Is 8 <= 9? Yes, code runs. i = 8 + 2.
  • i is 10. Is 10 <= 9? No, so loop ends.

If instead, you just used i + 2

  • i is 0. Is 0 <= 9? Yes, code runs. 0 + 2 (no change to i).
  • i is 0. Is 0 <= 9? Yes, code runs. 0 + 2 (no change to i).
  • i is 0. Is 0 <= 9? Yes, code runs. 0 + 2 (no change to i).
  • i is 0. Is 0 <= 9? Yes, code runs. 0 + 2 (no change to i).
  • …and so on, forever
1 Like

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