Fouad Tabbara
Fouad Tabbara

Reputation: 51

for loop with arithmetic expression

Can I use arithmetic expressions in a for loop?

e.g.

<script>
   var i=2;

   for(i=2;i<10;i+2){
      document.write(i);
   }
</script>

Upvotes: 4

Views: 782

Answers (2)

Tobias
Tobias

Reputation: 7771

The problem is not adding 2 to i, but that i+2 is not an assignment, so it will result in an infinite loop. You can write it like this:

var i;
for(i = 2; i < 10; i += 2){
  document.write(i);
}

i += 2 means "add 2 to i and store the result in i", basically twice i++.

Example fixed here.

Example with infinite loop here

Upvotes: 5

Nina Scholz
Nina Scholz

Reputation: 386868

With addition assignment:

The addition assignment operator adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator. Addition or concatenation is possible. See the addition operator for more details.

for (i = 2; i < 10; i += 2) {
//                    ^^

Example:

var i =0;
for (i = 2; i < 10; i += 2) {
    document.write(i + '<br>');
}

Upvotes: 2

Related Questions