All Types of Star, Number, and Character Patterns in JavaScript

Introduction Pattern printing is one of the most common exercises to master loops and logic-building in JavaScript. In this post, we will cover various types of patterns using nested loops and simple loops. These patterns include stars, numbers, and characters, and they help in improving coding logic. 1. Star Patterns in JavaScript 1.1 Right-Angled Triangle Pattern let n = 5; for (let i = 1; i

Mar 1, 2025 - 01:32
 0
All Types of Star, Number, and Character Patterns in JavaScript

Introduction
Pattern printing is one of the most common exercises to master loops and logic-building in JavaScript. In this post, we will cover various types of patterns using nested loops and simple loops. These patterns include stars, numbers, and characters, and they help in improving coding logic.

1. Star Patterns in JavaScript
1.1 Right-Angled Triangle Pattern

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

Output

*
* *
* * *
* * * *
* * * * *

1.2 Inverted Right-Angled Triangle

let n = 5;
for (let i = n; i >= 1; i--) {
    let row = '';
    for (let j = 1; j <= i; j++) {
        row += '* ';
    }
    console.log(row);
}

output

* * * * *
* * * *
* * *
* *
*

1.3 Pyramid Pattern

let n = 5;
for (let i = 1; i <= n; i++) {
    let row = ' '.repeat(n - i) + '* '.repeat(i);
    console.log(row);
}

output

    *
   * *
  * * *
 * * * *
* * * * *

2. Number Patterns in JavaScript
2.1 Increasing Number Triangle

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

output

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

2.2 Number Pyramid

let n = 5;
for (let i = 1; i <= n; i++) {
    let row = ' '.repeat(n - i) + (i + ' ').repeat(i);
    console.log(row);
}

output

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

3. Character Patterns in JavaScript
3.1 Alphabet Triangle

let n = 5;
for (let i = 1; i <= n; i++) {
    let row = '';
    for (let j = 0; j < i; j++) {
        row += String.fromCharCode(65 + j) + ' ';
    }
    console.log(row);
}

output

A
A B
A B C
A B C D
A B C D E

3.2 Character Pyramid

let n = 5;
for (let i = 0; i < n; i++) {
    let row = ' '.repeat(n - i - 1);
    for (let j = 0; j <= i; j++) {
        row += String.fromCharCode(65 + j) + ' ';
    }
    console.log(row);
}

output

    A
   A B
  A B C
 A B C D
A B C D E

Conclusion

These are some of the most common Star, Number, and Character Patterns in JavaScript. Practicing these nested loops and string manipulations will strengthen your problem-solving skills and logic-building. Try modifying the code for different patterns.