Patterns and small projects · beginner
JavaScript Program to Print a Star Pattern (Pyramid)
Print star patterns in JavaScript: a right triangle, a centred pyramid and an inverted triangle, using nested loops and String.prototype.repeat().
- for loops
- repeat()
- string building
- nested loops
Pattern programs test whether you can turn a picture into loop counters. For a pyramid of 5 rows, row i (from 1) needs 5 - i spaces and 2 × i - 1 stars.
console.log always ends the line, so each row is built as a string first and printed in one call.
The program
const rows = 5;
for (let i = 1; i <= rows; i++) {
console.log("*".repeat(i));
}
console.log("");
for (let i = 1; i <= rows; i++) {
console.log(" ".repeat(rows - i) + "*".repeat(2 * i - 1));
}*
**
***
****
*****
*
***
*****
*******
*********How it works
- The loop counts rows from 1 to 5.
- "*".repeat(i) repeats the star i times, which draws a right-angled triangle.
- For the pyramid, " ".repeat(rows - i) adds the leading spaces that centre each row.
- "*".repeat(2 * i - 1) gives 1, 3, 5, 7 and 9 stars, so each row is two wider than the one above.
Watch it run line by line
Step through the pyramid loop and look at "Output so far": a new row appears with each step past console.log, while i tells you which row is being drawn.
“Visualize step by step” opens the program in the JavaScript Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.
Another way: Nested loops, the classic way
Without repeat(), an inner loop builds each row one star at a time. This is how the pattern is usually written in C or Java.
const rows = 4;
for (let i = rows; i >= 1; i--) {
let line = "";
for (let j = 0; j < i; j++) line += "* ";
console.log(line.trimEnd());
}* * * *
* * *
* *
*Common mistakes
- Calling console.log inside the inner loop, which prints every star on its own line.
- Starting the loop at 0, which prints an empty first row.
- Passing a negative count to repeat(), which throws RangeError.
- Counting the stars as 2 × i instead of 2 × i - 1, which makes every row one star wider and the pyramid lopsided.
Try it yourself
- Print a diamond: the pyramid followed by the inverted pyramid.
- Print a number triangle where row i shows 1 to i.
Open the program in the JavaScript Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 JavaScript examples, or write your own program in the online JavaScript Compiler.