Code highlights logo



Nested Loops

Nested loops offer a powerful way to handle complex patterns and relationships within a data structure. By nesting loops, we can break down complex problems into smaller, more manageable tasks. This can greatly improve code organization, readability, and maintainability.

Syntax of Nested Loops

The syntax for creating nested loops is straightforward. It involves placing one loop inside the body of another loop. Here's an example of nested loops using the for loop:

1for (let i = 0; i < 5; i++) {
2 for (let j = 0; j < 5; j++) {
3 console.log(`i: ${i}, j: ${j}`);
4 }

In the above code snippet, we have two nested for loops. The outer loop iterates over the values of i, while the inner loop iterates over the values of j. This combination results in a total of 25 iterations, with each iteration printing the current values of i and j.

Example Application: Generating Patterns

One practical application of nested loops is generating patterns. By carefully manipulating the loop variables and combining them with conditional statements, we can create a wide variety of patterns.

Let's consider a simple example where we want to print a pyramid pattern using asterisks (*). We can achieve this by using nested loops as follows:

1for (let i = 0; i < 5; i++) {
2 let row = "";
3 for (let j = 0; j <= i; j++) {
4 row += "* ";
5 }
6 console.log(row);

The above code will output the following pattern:

2* *
3* * *
4* * * *
5* * * * *

By manipulating the loop variables and the actions performed within the loops, we can create more complex and visually appealing patterns.



Inside the inner loop, add a condition to only log the values of i and j if the value of i is greater than j.
You should see the following output after running it:

1"i: 2, j: 1"
2"i: 3, j: 1"
3"i: 3, j: 2"

Sign up to start coding

Already have an account?

Sign In

Course content