Codehs | 9.1.7 Checkerboard V2
// Set the size of the checkerboard
var squareSize = 50;
var rows = 8;
var cols = 8;
// Create the canvas
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// Function to draw a square
function drawSquare(x, y, color)
ctx.fillStyle = color;
ctx.fillRect(x, y, squareSize, squareSize);
// Draw the checkerboard
for (var row = 0; row < rows; row++)
for (var col = 0; col < cols; col++)
// Alternate between light and dark colors
var color = (row + col) % 2 === 0 ? 'lightgray' : 'gray';
drawSquare(col * squareSize, row * squareSize, color);
Bad Code:
for (let row = 1; row <= 8; row++) // Rows 1-8 instead of 0-7
Fix: In programming, grids almost always start at index 0. Use row < 8.
The "V2" autograder on CodeHS is stricter. It may check for: 9.1.7 Checkerboard V2 Codehs
Pro Tip: Run your code with a board size of 4x4 first to verify the pattern before scaling to 8x8.
Expected 4x4 pattern:
R B R B
B R B R
R B R B
B R B R
Use nested loops
Track color using a boolean
Better:
But wait — V2 often wants you to toggle based on previous square, not row+col.
Draw each square
Reset boolean for next row