DEV Community

D4nielRocha
D4nielRocha

Posted on

JavaScript Begginer Loop+Conditional question

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)

Collapse
 
savagepixie profile image
SavagePixie • Edited

1- Why we use (i % 2) in this case?

That checks if i is odd. It returns the remainder after diving i by two, on odd numbers it'll return 1 (which then gets evaluated to true) and on even numbers it'll return 0 (which counts as false).

This ensures that each line starts with a different symbol and that tiles alternate between the two symbols.

2-What does the ? symbol represents on this statement?

It's called "ternary operator." It's shorthand for an if statement if you will.

line += (j % 2)?'#':' '; is basically the same as this:

if (j % 2) line += '#'
else line += ' '

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 😉

Collapse
 
d4nielrocha profile image
D4nielRocha • Edited

Thanks for the reply and also for explaning in a such a way that somewhat made it simpler for me to understand it.