0

I understand most of the code, but I am unsure why in the if statement you add x and y. What does this do? Also, what does the board += "\n"; accomplish?

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";
}

console.log(board);
j08691
  • 204,283
  • 31
  • 260
  • 272
  • 1
    What is this code supposed to do? – Wais Kamal Jun 05 '20 at 21:41
  • 2
    `board += "\n";` simply adds a "newline" or a "hard break" to the end of the string. – Zak Jun 05 '20 at 21:42
  • 1
    Have you tried running the code? It prints an 8x8 checkerboard pattern. The `(x + y) % 2` check is to know which character to print, the adding of the newline character after every row is, well, to put each row on a new line. – Robin Zigmond Jun 05 '20 at 21:43
  • https://stackoverflow.com/questions/6826260/how-does-plus-equal-work + https://stackoverflow.com/questions/1155678/javascript-string-newline-character – VLAZ Jun 05 '20 at 21:46

3 Answers3

4

The (x+y) is to ensure that either they are both even, or both odd. That ensures that you get that checker pattern that you see (if you need more explanation, look at the coordinates of a graph).

The \n is the newline character. Because just adding characters to the board would make it all one line, we need to put a newline character in between each row to make it look 2 dimensional.

Zak
  • 6,976
  • 2
  • 26
  • 48
0

This code is probably meant to generate an 8 by 8 checkerboard.

The line

if ((x + y) % 2 == 0)

checks whether the current square is evenly spaced or oddly spaced from both ends of the board. Two evenly spaced x and y sum up to an even number. Two oddly spaced x and y also sum up to an even number. When x and y sum up to an even number, a space character " " is printed. Otherwise, a hash "#" character is printed.

The line

board += "\n";

is intended to add a line break after each row.

Wais Kamal
  • 5,858
  • 2
  • 17
  • 36
0

Simply, it iterates for an 8*8= 64 times. The if statement stands for checking whether the addition of both x & y is even or odd if even adds space to the string board otherwise adds #. After each 8 iteration, it adds \n which stands for a newline.

Hazem Alabiad
  • 1,032
  • 1
  • 11
  • 24