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.
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.
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).
✏️ Worked example
Use the software design process to write a JavaScript nested loop that prints a 2x3 grid of stars (*).
1. Identify the subproblems: We need to handle rows (horizontal) and columns (vertical).
2. Plan the outer loop: This loop will run 2 times to create our 2 rows.
3. Plan the inner loop: Inside each row, we must print 3 stars for the 3 columns.
4. Write the JavaScript code: We put a 'for' loop for columns inside a 'for' loop for rows.
5. Combine the code: 'for (let r = 0; r < 2; r++) { let row = ""; for (let c = 0; c < 3; c++) { row += "*"; } console.log(row); }'
Want the full interactive lesson — quiz, animations, and Finn cheering them on?