Console.Log A Chessboard

11 Jun 2020 - Andrew McCall


        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:

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

When you have a program that generates this pattern, define a binding size = 8 and change the program so that it works for any size, outputting a grid of the given width and height.

Things To Learn Here

The first thing we want to do is define a couple of variables:

let size = 8;
let board = ' ';

This defines the height and the width that the board will be. we set board to an empty string to act as the first space of the board.

To accomplish this we need to go ahead and use a nested for loop.

for (let i = 0; i < size; i++) {
    for (let j = 0; j < size; j++) {
        if((i+j) % 2 === 0 ) {
            board += ' ';
        } else {
            board += '#';
    board += '\n';

basically we are checking each space with its corresponding space to see if it is even or odd. If it is even we are outputting a blank space. If it is odd we are outputting an octothorpe. We use the modulus operator to determine this.

board += '\n'; tells us to make a line break at the end of the line.

The basics of a for loop are setting a starting index, which is usually 0, setting a limit which is usually a number or array length, and then incrementing the loop index until all indexes have been exhausted.

for example:

let list = new Array(1,2,3,4,5);

for (let i = 0; i < list.length; i++) {

This will output the following to the console:


I think that pretty much wraps up my loose understanding of nested lists.

If you have any questions or find any errors feel free to reach out to me here.

chevron_left Intersection Observer API
Quickly Connect To MongoDB In NodeJS chevron_right
Tags: for loop, javascript, learn to code, web development