Bummer! You must be logged in to access this page.

Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Create a chess board with hashtags

Hello,

I have a JS exercise and it is to create a chess board using hashtags (#). After trying to solve it myself I gave in and looked at the proper code from the answers page.

Here it is

var size = 8;

var board = "";

for (var y = 0; y < size; y++) {
  for (var x = 0; x < size; x++) {
    if ((x + y) % 2 == 0)
      board += " ";
    else
      board += "#";
  }
  board += "\n";
}
console.log(board);

And here is a screenshot of the output. http://www.evernote.com/shard/s264/sh/1242047c-af85-4762-a43f-2338675c318b/0e53aa00615541295cbe2f3a879992c9

Can somebody explain the logic behind this code and how it works. (also perhaps some alternative ways to solving the same problem)

1 Answer

var size = 8;

var board = "";

for (var y = 0; y < size; y++) {
  for (var x = 0; x < size; x++) {
    if ((x + y) % 2 == 0)
      board += " ";
    else
      board += "#";
  }
  board += "\n";
}
console.log(board);

You define the board size (it is a square, so equal columns and rows)

You initialise the board to an empty string

You loop 8 times for the rows

Within the rows loop, you loop 8 times for the columns

If the sum is divisible by 2 (the % operator is called modulus and returns the remainder of a division), then add a space to the board, otherwise add a hashtag (shorter - for every other square, add a hashtag)

When the columns loop is over, add a carriage return and new line

When the rows loop is over, print out the board

Thanks