JavaScript Program to Print Triangle Star Pattern
Last Updated :
06 May, 2024
This article will show you how to make a triangle star pattern using JavaScript. We’ll use a for loop to iterate through the number of rows, and in each iteration 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 stars in each iteration. Additionally, we’ll create a whitespace string to add the necessary spaces before the stars to ensure proper alignment. Below are the star patterns we’ll cover:
1. Upper left triangle
The upper left triangle is a right-angled triangle that has the maximum number of stars at the left side and the bottom. We will use a for loop and repeat() method of string to print this pattern.
Example 1: The below code example contains the code that prints an upper left triangle.
Javascript
let n = 5;
for (let i = 1; i <= n; i++) {
let str = "* ";
console.log(str.repeat(i));
}
Output*
* *
* * *
* * * *
* * * * *
2. Upper right triangle
The pattern of this triangle contains the maximum number of start at the right side and the bottom. It is another type of right-angled triangle.
Example 2: The below example explains the logic to print the 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 *
* *
* * *
* * * *
* * * * *
3. Lower Right Triangle
The lower right triangle has the maximum number of stars at the top and the right side. It is also an right-angled triangle.
Example 3: The below code example will illustrate the logic to print the ower right triangle 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* * * * *
* * * *
* * *
* *
*
4. Lower Left Triangle
The lower left triangle has the maximum number of stars at the top and the left side. It is also a type of right-angled triangle.
Example 4: The below code example uses the logi to print the lower left triangle star pattern.
Javascript
let n = 5;
for (let i = n; i >= 1; i--) {
let str = "* ";
console.log(str.repeat(i));
}
Output* * * * *
* * * *
* * *
* *
*
Share your thoughts in the comments
Please Login to comment...