1

I'm just going through freedcodecamp and I'm doing the "Iterate Odd Numbers With a For Loop" section. I just have a question with regards to some unintended effects I encountered.

const myArray = [];

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

This is the correct answer and I got there no problem, however I'm wondering why changing the i += 2 to i + 2 generates an infinite loop?

isherwood
  • 58,414
  • 16
  • 114
  • 157
  • 8
    because `i` does not change. – Nina Scholz Jan 14 '22 at 19:29
  • ... therefore the condition `i < 10` is never `false` – Parzh from Ukraine Jan 14 '22 at 19:29
  • Hi Nina, I'm very very new to this, could you please explain why it doesn't change? When going through the tutorials it described += as a shorter way to type a var + number = and that was the only benefit it outlined. – Ryan Nuttall Jan 14 '22 at 19:30
  • 1
    @RyanNuttall Please refer to [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for) – Parzh from Ukraine Jan 14 '22 at 19:31
  • 2
    Because ```i + 2``` is not an assignment, it is an operation, so ```i``` will always remain ```1```, so each time will simply return ```3``` being less than ```10``` – prettyInPink Jan 14 '22 at 19:32
  • 3
    Thanks for all your comments, the explanations and links have helped me understand it. – Ryan Nuttall Jan 14 '22 at 19:34
  • 1
    `i += 2`, a shorthand for `i = i + 2`, or **take value of i, adds 2 to it, then assign it back to i** . For your question, `i + 2`, which means **take value of i, adds 2 to it THEN do nothing with it** since there is no assignment – Luke Vo Jan 14 '22 at 19:36
  • 1
    To answer your earlier question, `i += 2` is shorthand for `i = i + 2`. It includes an assignment operator _and_ an arithmetic operator. – isherwood Jan 14 '22 at 19:37

0 Answers0