Why is there a comparison with 0
?
if (i% 3 == 0)
As I understand it, there is a division without a remainder, but I don’t understand why then compare.
Answer 1, authority 100%
This is a check that the remainder of dividing the number i
by another number (3
) is 0.
This is usually done in order to perform some action in a loop, but not every time (in this case, only every 3 times).
For example:
- color every 2nd line in the list with a different color
if (i% 2 == 0) ...
- show progress on the screen every 10 iterations
if (i% 10 == 0) ...
- split the stream of digits by adding a space after every 3
if (i% 3 == 0) ...
- etc.
Answer 2, authority 67%
The %
sign is to get the remainder of the division, in your case it is a check that the number i
is divisible by 3
.
You can read more about JS operators here
Answer 3, authority 11%
This is a modulus operator that returns the remainder of a division. For example, 18% 7
will equal 4
(roughly 18 - 14 = 4
). And if you check any number for zero, then you check if this number is evenly divisible by some one.