Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

1. Confusion over a loop

I am going through Eloquent Javascript and I am confused by a comparison that is made on after Ex 2.5

These two lines of code are given and the book states they are equivalent. I see the output gives the same result and I understand that % gives the remainder.

To me 2nd line of code should give the number 20 not 21 because 20/7 has a remained that is not equal to zero. My logic told me that the symbols for both of these should be == and not !=, but my logic or something about my think is obviously off on the problem.

Code:
```for (var current = 20; ; current++) {
if (current % 7 == 0)
break;
}
print(current);```
2nd segement

Code:
```for (var current = 20; current % 7 != 0; current++)
;
print(current);```
Any assistance is appreciated.

• Originally Posted by codenogood
To me 2nd line of code should give the number 20 not 21 because 20/7 has a remained that is not equal to zero.
Yes you are correct , it is 20
the first iteration of the loop.
The second it is 21 and satisfies
the condition so break is executed and
the code breaks out of the loop so
the print statement is executed.

Code:
```
for (var current = 20; ; current++) {
if (current % 7 == 0)//first iteration current is 20, current % 7 = 6
// condition (current % 7 == 0) is not satisfied
//next iteration current is 21, current % 7 = 0 so
//condition is satisfied and break is executed
break;// when break is executed the code breaks out of the loop
}
print(current);```
in this code the condition is in a different place and
must be satisfied to continue the loop

Code:
```for (var current = 20; current % 7 != 0; current++)//first iteration current is 20
;//current % 7 is 6 so the condition is satisfied and the loop continues
//second iteration current is 21
//current % 7 is 0
//which does not satisfy the condition
// so the loop terminates and the print statement is executed
print(current);```
To sum up, in the first code
the break command is used
to terminate the loop, in the
second code the loop terminates
normally.

I hope this clarifies the code, please
ask more questions and good luck to

• Users who have thanked DaveyErwin for this post:

codenogood (12-30-2013)

• After re-reading several times this makes sense now. Thank you

•

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•