4

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>
3
  • Have you tried it? Did it work? Commented Jan 11, 2016 at 17:17
  • You shouldn't be declaring the variable that you are using for the loop. Unless you need to use it elsewhere once the loop is done. Commented Jan 11, 2016 at 17:18
  • 3
    Yes you can. But i+2 by itself will compute i+2 and discard the results (the value of i won't change). Perhaps you mean i += 2. Commented Jan 11, 2016 at 17:22

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

2

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>');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.