Thursday, September 4, 2025
HomeLanguagesJavascriptJavaScript Program to Print Triangle Star Pattern

JavaScript Program to Print Triangle Star Pattern

This article will demonstrate how to create a triangle star pattern in JavaScript.

The Possible Triangle Star Patterns are:

  • Upper left triangle
  • Upper right triangle
  • Lower right triangle
  • Lower left triangle

Approach

To create the triangle start patterns in javascript, we will use a for loop for the n number of iterations, and in each loop we will print the “*” with the repeat method to increase or decrease the number of starts in each iteration. Also to provide proper space create a whitespace string to give the required space before the stars.

Example 1: Upper Left Triangle.

Javascript




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


Output

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

Example 2: Upper Right Triangle.

Javascript




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


Output:

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

Example 3: Lower Right Star Pattern

Javascript




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


Output:

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

Example 4: Lower Left Star Pattern

Javascript




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


Output

* * * * * 
* * * * 
* * * 
* * 
* 
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6629 POSTS0 COMMENTS
Nicole Veronica
11799 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11859 POSTS0 COMMENTS
Shaida Kate Naidoo
6749 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6698 POSTS0 COMMENTS
Umr Jansen
6718 POSTS0 COMMENTS