Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 900
Fouad Tabbara Avatar asked Feb 09 '23 01:02

Fouad Tabbara


2 Answers

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

like image 62
Tobias Avatar answered Feb 19 '23 01:02

Tobias


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>');
}
like image 42
Nina Scholz Avatar answered Feb 19 '23 00:02

Nina Scholz