0
for (var i = 10; i < 41; i+2) {
    console.log(i);
}

I am learning basic javascript and when I ran this on chrome, it crahsed. I think the loop going infinite but I don't understand why.

But when I change i + 2 to i++, it works fine.

I am trying to print out even numbers between 10 and 40 that's why I changed i + 2 to i++.

Am I not allowed to make i increment by 2?

Barry
  • 3,303
  • 7
  • 23
  • 42
user3000482
  • 185
  • 1
  • 2
  • 8

4 Answers4

6

You never change the value of i. Your expression is not an assignment of a value to i.

You need an addition assignment +=

i += 2

for (var i = 10; i < 41; i += 2) {
    console.log(i);
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Try this:

for (var i = 10; i < 41; i = i+2) {
    console.log(i);
}

or

for (var i = 10; i < 41; i +=2) {
    console.log(i);
}
Mans
  • 2,953
  • 2
  • 23
  • 32
1

You need to store the value back into the variable.

                         ↓↓
for (var i = 10; i < 41; i=i+2) {
    console.log(i);
}
mariamelior
  • 91
  • 1
  • 7
  • I removed the asterisks from the code. They were meant to call attention to your change, but might be confusing to beginner programmers, who could easily misinterpret the asterisks as part of the code. –  Aug 17 '18 at 19:27
1

Just writing i+2 calculates the new value, but it doesn't store it back in the variable.

To increment i by 2, you need to write:

i = i + 2

or the shorthand:

i += 2

It works when you write i++ because that's short for

i = i + 1
Barmar
  • 741,623
  • 53
  • 500
  • 612