Hi there,
I've just started to study javascript and I'm reading the Eloquent Javascript book, recommended by several friends and websites I've read.
I just finished the 3 chapter where I had to write one particular piece of code to answer to one of the challenges on the book. I couldn't do it at first and them I looked at the answer provided by the book, and I still can't figure it out why it was done like that.
Could somebody try to explain me in a better way as to why this code is written like this? Thank you so much for all replies.
var size = 8;
for (var i = 1; i <= size; i++) {
var line = (i % 2)?'':' ';
for (var j = 1; j < size; j++) {
line += (j % 2)?'#':' ';
}
console.log(line);
}
The task was to write a code that would produce a table chess with spaces and # simbols with a size of 8x8.
What I can't quite understand is:
1- Why we use (i % 2) in this case?
2-What does the ? symbol represents on this statement?
Top comments (2)
That checks if
iis odd. It returns the remainder after divingiby two, on odd numbers it'll return1(which then gets evaluated totrue) and on even numbers it'll return0(which counts asfalse).This ensures that each line starts with a different symbol and that tiles alternate between the two symbols.
It's called "ternary operator." It's shorthand for an
ifstatement if you will.line += (j % 2)?'#':' ';is basically the same as this:By the way, in the future, you can use the tag #help when you need help with code. It'll attract more people willing to help 😉
Thanks for the reply and also for explaning in a such a way that somewhat made it simpler for me to understand it.