Studyfin Studyfin ✨ Sign up free

Intro to JavaScript

Grade 8 · Coding · Free lesson

Hi! I'm Studyfin, your coding tutor. Today, we will learn how to write cool nested loops in JavaScript to solve real problems!

In coding, we use a software design process to plan our work. First, we understand our main problem, break it into smaller subproblems, and then write our code.

icon

A nested loop is simply a loop inside another loop. The outer loop runs once, and then the inner loop runs all its steps before the outer loop moves to its next turn.

Outer Loop Inner Loop

Let us think about a real-world context like building a grid of lights. To solve this, we split it into two subproblems: drawing rows (the outer loop) and drawing columns (the inner loop).

Row 1 (Outer Loop Step 1): Row 2 (Outer Loop Step 2): Row 3 (Outer Loop Step 3):
✏️ Worked example

Use the software design process to write a JavaScript nested loop that prints a 2x3 grid of stars (*).

  1. 1. Identify the subproblems: We need to handle rows (horizontal) and columns (vertical).
  2. 2. Plan the outer loop: This loop will run 2 times to create our 2 rows.
  3. 3. Plan the inner loop: Inside each row, we must print 3 stars for the 3 columns.
  4. 4. Write the JavaScript code: We put a 'for' loop for columns inside a 'for' loop for rows.
  5. 5. Combine the code: 'for (let r = 0; r < 2; r++) { let row = ""; for (let c = 0; c < 3; c++) { row += "*"; } console.log(row); }'
technology
Want the full interactive lesson — quiz, animations, and Finn cheering them on?

More Coding lessons