r/JavaScriptTips • • Jun 02 '22

Problem with understanding checkerboard code

Hi, I am working on an exercise in a textbook and I am struggling to understand how the code works, the code produces a 8X8 checkerboard of alternating spaces and hashtags based on whether two loops starting at 0 and incremented by 1 per cycle is odd or even.

  1. x++ and y ++ mean to increase variable by 1 but use the original value so;

-1st Loop will be (x + y) = 0 + 0

-2nd Loop will be 1 + 1 3rd will be 2 + 2 etc - thus accounting for all even numbers and so printing " "

within the board = ""

But how is the code testing for odd numbers when they increment and are added together in such a way to only produce even numbers? How is the else activated?

If the code produces horizontal lines of alternating spaces and hashtags until it reaches up to 8 (board += "\n"), what part of the code is telling it to stop at 8 lines vertically?

` let size = 8;

let board = "";

for (let y = 0; y < size; y++) {
for (let x = 0; x < size; x++) {
if ((x + y) % 2 == 0) {
board += " ";
} else {
board += "#";
}
}
board += "\n";
}
4 Upvotes

2 comments sorted by

View all comments

3

u/IHateAds23 Jun 03 '22

Hi, I made it visual for your: https://imgur.com/ou2iCuF
Both for loops are limited by let size = 8
For loop y will iterate and during every iteration will call for loop x. This means the board will start with a hashtag ((0+0)modulo2 is zero), and blank in the next iteration of x ((0+1)modulo2 == 1)After every x loop, the board will add \n.

So no, it will not be 0 + 0, 1 + 1, 2 + 2, but just like u/sam_codes_ said: 0 + 0, 0 + 1, 0 + 2