Glendon Philipp Baculio - 6 months ago 67

Javascript Question

I am sorry for being noob but I think I am in the right place. I have been trying to solve chess board of eloquent javascript but it is so hard for me, even the solution provided:

`var size = 8;`

var board = "";

for (var y = 0; y < size; y++) { /* why 2 loops? */

for (var x = 0; x < size; x++) {

if ((x + y) % 2 == 0) /* why is this? */

board += " ";

else

board += "#";

}

board += "\n";

}

console.log(board);

Can someone please explain lines further, I don't want to pass this problem without fully understanding.Also, Is this book also a good start for javascript?

Answer

The two loops are required to construct the two dimensions of the board. Have a look at:

You can think of the outer loop as the rows (the numbers on the board) and the inner loop as the columns (the alphabet on the board). Each loop of the outer loops creates another row, and each loop of the inner loop creates another column in said row.

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

uses the `%`

(modulo) to determine whether the `x + y`

divided by `2`

has a remainder. If the result is equal to `0`

then it had no remainder, and thus is an even number so log out a space, otherwise log out a `#`

, building your chess board pattern.

So for example the first square in the top left would be `(0 + 0) % 2`

resulting in `0`

so print a space, and the next square over would be `(0 + 1) % 2`

would be `1`

so print a `#`

.

In regards to the book Eloquent JavaScript by Marijn Haverbeke, yes it's definitely a great book. It covers a lot of topics are are divided into isolated chapters so it's great as a reference as well. Though one down side I personally found with the book is that in certain chapters the author uses very complex and convoluted examples to demonstrate the usage of JavaScript.

Source (Stackoverflow)

Comments