JavaScript: Chessboard Program

Exercise from Eloquent JavaScript

Bahay Gulle Bilgi
The Startup

--

Image by Devanath from Pixabay

Today, we will write a function that forms a chessboard. You can find the exercise in the Eloquent Javascript book (3rd edition, chapter 2; Program Structure).

Write a program that creates a string that represents an 8×8 grid, using newline characters to separate lines. At each position of the grid there is either a space or a “#” character. The characters should form a chessboard.

Passing this string to console.log should show something like this:

# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #
# # # #

Let’s start writing our function that takes a number as a parameter and generates a grid of the given size.

Here are the steps that we will follow to write this program:

  1. Declare a variable of an empty string that stores a space (“ ”) or a hash (“#”) or a newline (“\n”).
  2. Set a loop inside of a loop to generate a two dimensional grid: An outer loop is for rows to set board height (“i”) and the inner loop is for columns to set board width (“j”).
  3. Start building the string line by line from left to right and top to bottom by checking the sum of the two counters ((i + j)%2==0).
  4. If the sum of the two…

--

--