Studyfin Studyfin ✨ Sign up free

Intro to JavaScript

Grade 7 · Coding · Free lesson

Hi there! I am Studyfin, your friendly coding tutor. Today, we will learn how to design smart programs using nested loops in JavaScript!

When we design software, we use a step-by-step design process. We start by breaking a big problem down into smaller subproblems. Then, we write code to solve each part.

sitting

Sometimes, a subproblem requires repeating an action inside another repeating action. This is called a nested loop. In JavaScript, we put one loop inside another loop to make this happen.

Outer Loop (Runs 3 times)Inner Loop (Runs 4 times inside)

Let us look at a real-world context like building a grid of stars. The outer loop controls which row we are on. The inner loop draws each star in that row, solving our subproblem.

Row 1:Row 2:
✏️ Worked example

Use the software design process to create a text-based JavaScript program. This program must print a 2-row by 3-column grid of hashtags (#) to represent a simple map layout.

  1. Identify the subproblems: Subproblem A is moving down to the next row. Subproblem B is printing three hashtags side-by-side in the current row.
  2. Design the outer loop: This loop runs 2 times to handle our 2 rows of the grid.
  3. Design the inner loop: Inside the outer loop, create a loop that runs 3 times to print the 3 hashtags.
  4. Combine them into JavaScript code: Use 'for' loops and create a string variable to hold the characters for each row.
  5. Write the final code: 'for (let r = 0; r < 2; r++) { let rowStr = ""; for (let c = 0; c < 3; c++) { rowStr += "#"; } console.log(rowStr); }'
javascript
Want the full interactive lesson — quiz, animations, and Finn cheering them on?

More Coding lessons