Today, I took my first step into learning loops in JavaScript, especially the concept of nested for loops. As a fun practice, I used what I learned to create a simple chessboard layout using HTML, CSS, and JavaScript.
What is a for Loop?
A for loop lets us repeat a block of code a certain number of times. The basic syntax is:
for (let i = 0; i < 10; i++) {
// Code runs 10 times
}
What is a Nested for Loop?
A nested loop is a loop inside another loop. This is useful when dealing with grids or tables — like a chessboard!
The Project: Chessboard Generator
Here’s the code I wrote to generate an 8x8 chessboard pattern:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Chessboard</title>
<style>
#box {
border: 1px solid;
width: 60px;
height: 60px;
}
.chessboard {
display: grid;
grid-template-columns: repeat(8, 60px);
}
.white-box {
background-color: aliceblue;
}
.black-box {
background-color: black;
}
</style>
</head>
<body>
<div class="chessboard"></div>
<script>
let board = document.querySelector(".chessboard");
for (let row = 1; row <= 8; row++) {
for (let col = 1; col <= 8; col++) {
let box = document.createElement("div");
box.setAttribute("id", "box");
if ((row + col) % 2 === 0) {
box.setAttribute("class", "white-box");
} else {
box.setAttribute("class", "black-box");
}
board.appendChild(box);
}
}
</script>
</body>
</html>
How It Works:
I used a grid layout with display: grid and grid-template-columns: repeat(8, 60px) to define the chessboard layout.
I used two for loops to create 8 rows and 8 columns.
I used (row + col) % 2 === 0 to alternate between white and black squares.
What I Learned
How to use for loops and nested for loops.
How to dynamically create and style HTML elements using JavaScript.
How math logic like % (modulus) helps alternate patterns — very useful for building things like checkerboards or tables.
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.