Open In App

JavaScript Program to Print Pyramid Star Pattern

In this article, we will demonstrate how to create pyramid star patterns in JavaScript.

The Possible Pyramid Star Patterns are:

Approach

There will be two different approaches based on alignments i.e. horizontal and vertical.



Horizontally Inverted Pyramid

Vertically Inverted Pyramid

Example 1: Upper pyramid




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

Output

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

Example 2: Inverted pyramid




let n = 5;
for (let i = n; i >= 1; i--) {
    let str = "* ";
    let space = '  ';
    console.log(space.repeat((n - i)) + str.repeat(i * 2 - 1));
}

Output
* * * * * * * * * 
  * * * * * * * 
    * * * * * 
      * * * 
        * 

Example 3: Left inverted pyramid




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

Output
        * 
      * * 
    * * * 
  * * * * 
* * * * * 
  * * * * 
    * * * 
      * * 
        * 

Example 4: Right inverted pyramid




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

Output
* 
* * 
* * * 
* * * * 
* * * * * 
* * * * 
* * * 
* * 
* 

Article Tags :