Codiqo

Learn JavaScript · lesson 21 of 60 · about 8 minutes

Nested Loops and Building Strings

Draw the visitor's streak as a calendar: put a loop for the days inside a loop for the weeks, and grow each row one square at a time.

What you'll learn

  • Write a nested loop
  • Build a string inside a loop
  • Use repeat() for patterns

A streak calendar

The streak line shows stars in a row, but a long streak gets hard to read. Sam wants a calendar instead: four weeks, one row per week, a ■ for every day the visitor coded and a □ for the rest. That's a loop for the weeks with a loop for the 7 days inside it, and each row is a string built one square at a time.

Loops inside loops

When one loop sits inside another, the inner loop runs all of its laps for every lap of the outer loop. Rows and columns are the classic use.

A times table grid

for (let row = 1; row <= 3; row++) {
  let line = "";
  for (let col = 1; col <= 3; col++) {
    line += String(row * col).padStart(3);
  }
  console.log(line);
}

Output

  1  2  3
  2  4  6
  3  6  9

Growing a string

Start with an empty string "" and add to it with +=. For simple repetition, "*".repeat(3) gives "***".

A staircase

for (let i = 1; i <= 4; i++) {
  console.log("#".repeat(i));
}

Output

#
##
###
####

The calendar for a 10-day streak

const theirDays = 10;
// four weeks of the visitor's streak, a square for each day
let calendar = "";
for (let week = 0; week < 4; week++) {
  let row = "";
  for (let day = 0; day < 7; day++) {
    row += week * 7 + day < theirDays ? "■" : "□";
  }
  calendar += row + "\n";
}
document.querySelector("#calendar").textContent = calendar.trim();

Tip

Day d of week w is square number w * 7 + d, counting from 0, so the 10th day of a streak (number 9) is the third square of the second row.

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.