I've just started to learn JS and I'm having a bit of trouble understanding the basics behind the 'for' loop.
Example:
for (var number = 3; number % 7 == 0; number++)
Why doesn't it make sense? Why do I have to write it down like that:
for (var number = 3; ; number++) {
if (number % 7 == 0)
break;
}
Thank you for help!
I've just started to learn JS and I'm having a bit of trouble understanding the basics behind the 'for' loop.
Example:
for (var number = 3; number % 7 == 0; number++)
Why doesn't it make sense? Why do I have to write it down like that:
for (var number = 3; ; number++) {
if (number % 7 == 0)
break;
}
Thank you for help!
Share Improve this question asked Jun 14, 2016 at 22:49 no use for a nameno use for a name 6687 silver badges16 bronze badges 4-
3
The middle part of the loop tells you the condition that makes it keep running, not the condition that makes it stop. Therefore, to achieve the piece of code on the bottom, you should have used
number % 7 != 0
instead of==
– dabadaba Commented Jun 14, 2016 at 22:54 - Thank you! That was the point! – no use for a name Commented Jun 14, 2016 at 22:59
- 1 You should accept @melpomene's answer. – dabadaba Commented Jun 14, 2016 at 23:00
- I'm going to, but I've some error atm while pressing the button. – no use for a name Commented Jun 14, 2016 at 23:03
1 Answer
Reset to default 4You've inverted the condition. The middle part of a for
loop tells you what must be true for the loop to continue. Your second version uses the same condition to decide when to stop.
for (A; B; C) { ... }
can be (mostly) rewritten as
A;
while (B) {
...
C;
}
(The difference is that continue
in a for
loop will still execute the C
part.)
Initially your number
is 3. Then we do the equivalent of while (number % 7 == 0) { ... }
, but that condition fails (3 % 7
is 3, not 0), so the loop never runs.
You probably wanted
for (var number = 3; number % 7 != 0; number++)