How to usenested loops in Javascript

In this approach Nested loops iterate through rows and columns, incrementing row count in the outer loop and column count inner loop, to print desired patterns or structures like right angled trangle.

Example: We are using nested loops to print a number pattern with increasing numbers on each line, up to the specified limit of 5.

Javascript




const n = 5;
for (let i = 1; i <= n; i++) {
    let str = '';
    for (let j = 1; j <= i; j++) {
        str += j + ' ';
    }
    console.log(str);
}


Output

1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 

JavaScript Program to Print Number Pattern

The idea of pattern-based programs is to understand the concept of nesting for loops and how and where to place the alphabet/numbers/stars to make the desired pattern.

These are the following approaches to printing different types of number patterns:

Table of Content

  • Using nested loops
  • Using array manipulation and join() method

Similar Reads

Approach 1: Using nested loops

In this approach Nested loops iterate through rows and columns, incrementing row count in the outer loop and column count inner loop, to print desired patterns or structures like right angled trangle....

Approach 2: Using array manipulation and join() method

...