Understanding Nested Loops in JavaScript
This article is a complementary resource to the Learn JavaScript Basics course.
This article is a complementary resource to the Learn JavaScript Basics course.
In programming, loops allow us to repeat a block of code multiple times. But what if we need to handle multiple levels of repetition? This is where nested loops come in.
A nested loop is simply a loop inside another loop. This is useful when working with multi-dimensional structures, grids, patterns, and combinations of elements.
Before diving into practical examples like drawing shapes with loops, let’s first understand how nested loops work by looking at a simple example of combining two lists.
Imagine you have two lists: one containing car attributes and another containing car brands. If we want to print all possible combinations, we can use nested loops.
// List of car attributes
let attributes = ["Electric", "Fast"];
let cars = ["Tesla", "Porsche"];
for (let attribute of attributes) {
for (let car of cars) {
console.log(attribute, car);
}
}
Output:
Electric Tesla Electric Porsche Fast Tesla Fast Porsche
attributes
array. It first picks "Electric", then "Fast".cars
list.Now that we understand the basics of nested loops, let's apply this concept to build different patterns using loops.
Imagine you want to draw a square using stars (*
) like this:
* * * * * * * * *
for (let i = 0; i < 3; i++) {
let row = "";
for (let j = 0; j < 3; j++) {
row += "* ";
}
console.log(row);
}
Output:
* * * * * * * * *
Now, let’s say we want a triangle instead of a square:
* * * * * * * * * * * * * * *
let height = 5;
for (let i = 1; i <= height; i++) {
let row = "";
for (let j = 0; j < i; j++) {
row += "* ";
}
console.log(row);
}
Output:
* * * * * * * * * * * * * * *
Now, let's reverse the logic to make an inverted right-angled triangle:
* * * * * * * * * * * * * * *
let height = 5;
for (let i = height; i > 0; i--) {
let row = "";
for (let j = 0; j < i; j++) {
row += "* ";
}
console.log(row);
}
Output:
* * * * * * * * * * * * * * *
By following this step-by-step thinking process, you’ll be able to build any pattern using nested loops in JavaScript!