var res = '\n', i, j;
for (i = 1; i <= 7; i++) {
for (j = 1; j <= 15; j++) {
res += (i * j) % 8 ? ' ' : '*';
}
res += '\n';
}
alert(res);
(Copy / Pasted from Object-Oriented JavaScript - Third Edition, Ved Antani, Stoyan Stefanov)
Trying to understand this loop. I understand what's happening but not why.
res += (i * j) % 8 ? ' ' : '*';
I'm reading the ternary operator as follows.
- boolean expression:
(i * j) % 8
- execute if true: concatenate space with
res
- execute if false: concatenate asterisk with
res
On the first iteration, when it comes to the inner loop, it only outputs '*', when the modulo is 0, all other times it outputs ' '.
Why does it do this?
Also, don't understand the first line. What is the following doing?
var res = '\n', i, j;
What is the purpose of assigning the variable res
to 3 values.
In the console it works fine without this line.