How to make a triangle in JavaScript

This article explains how to create a triangle in JavaScript, complete with an example code.

Creating a Triangle in JavaScript

In this example, we will use JavaScript to create a triangle. To do this, we will use a for loop to print out a series of asterisks, creating a triangle shape.


for (let i = 0; i < 5; i++) {
    let output = '';
    for (let j = 0; j <= i; j++) {
        output += '*';
    }
    console.log(output);
}

The first part of the loop initializes the variable i to 0 and it will loop 5 times. In each iteration, the value of i will increase by 1.

The second part of the loop initializes the variable j to 0 and it will loop until the value of j is equal to the value of i. In each iteration, the value of j will increase by 1.

The output of the code will be:


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

As you can see, the output is a triangle shape made up of asterisks.

This is just one way of creating a triangle in JavaScript. There are many other ways to achieve the same result.

Answers (0)