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)); } |
* * * * * * * * * * * * * * *
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)); } |
* * * * * * * * * * * * * * *