Print a star pattern (triangle and pyramid) in JavaScript
Beginner · 4 min read
Printing a triangle of stars is one of the first loop exercises almost everyone meets. It looks like a toy, but it practices something you use all the time: working out how many of something to draw on each line, from the line number. The same thinking draws progress bars, text charts and indented menus.
In this tutorial you will build two shapes, a left-aligned triangle and a centered pyramid, using repeat instead of a second loop. You will collect the lines in an array and return it, so the result can be checked. You need to know how a for loop works and what an array is.
repeat: one line instead of a loop
repeat(n) gives you a piece of text written n times in a row:
console.log('*'.repeat(3)); // ***
console.log('ab'.repeat(2)); // abab
console.log('*'.repeat(0).length); // 0
The classic way to draw these shapes uses two nested loops and adds one star at a time. repeat replaces the inner loop completely.
Return the lines, then print
If you call console.log inside the loop, the shape appears on screen and nothing is left to check. If you push each line into an array and return it, you can test the array, and print it all at once with join('\n'). '\n' is the newline character, so join puts each line on its own row.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
80 A triangle of stars
easyPrint a left-aligned triangle of stars rows tall, then a centred pyramid. Return the lines rather than printing inside the loop, so they can be checked.
Stuck? Three hints, smallest first
- 1.
'*'.repeat(n)saves you the inner loop entirely. - 2. A pyramid row is
rows - ispaces then2 * i - 1stars. - 3. Collect lines into an array and
join('\n')once at the end.
Step 1: the left triangle
Row 1 has one star, row 2 has two, and so on. The row number is the star count:
function leftTriangle(rows) {
const lines = [];
for (let i = 1; i <= rows; i++) lines.push('*'.repeat(i));
return lines;
}
console.log(leftTriangle(4)); // [ '*', '**', '***', '****' ]
console.log(leftTriangle(4).join('\n'));
The second line prints the shape:
*
**
***
****
Starting i at 1 instead of 0 is what makes this neat. It runs from 1 to rows, and each value is exactly the number of stars that row needs, so there is no + 1 to get wrong.
Step 2: check it without looking
Because the function returns an array, you can test it with numbers:
function leftTriangle(rows) {
const lines = [];
for (let i = 1; i <= rows; i++) lines.push('*'.repeat(i));
return lines;
}
console.log(leftTriangle(4).join('').length); // 10
console.log(leftTriangle(0)); // []
1 + 2 + 3 + 4 is 10 stars. Asking for zero rows gives an empty array, and no error.
Step 3: work out the pyramid
A centered pyramid needs spaces in front of each row. Look at a pyramid 4 rows tall:
*
***
*****
*******
Count each row:
- Row 1: 3 spaces, 1 star
- Row 2: 2 spaces, 3 stars
- Row 3: 1 space, 5 stars
- Row 4: 0 spaces, 7 stars
The spaces go down by one each row: rows - i. The stars go up by two each row, always an odd number: 2 * i - 1.
Step 4: the pyramid in code
function pyramid(rows) {
const lines = [];
for (let i = 1; i <= rows; i++) {
lines.push(' '.repeat(rows - i) + '*'.repeat(2 * i - 1));
}
return lines;
}
console.log(pyramid(3)); // [ ' *', ' ***', '*****' ]
console.log(pyramid(5)[4].length); // 9
console.log(pyramid(6).every((line) => line.trim().length % 2 === 1)); // true
The bottom row of a 5-row pyramid is 9 stars wide, which is 2 * 5 - 1. The last line uses trim() to remove the spaces and checks that every row has an odd number of stars. The rows have no spaces on the right, because nothing needs to follow the stars.
Step 5: a negative count
What happens if repeat gets a negative number, for example from a mistake in the space formula?
try {
'*'.repeat(-1);
} catch (err) {
console.log(err.name); // RangeError
}
repeat throws an error instead of quietly giving empty text. That helps: a wrong sign shows up at once, instead of printing a strange or blank shape.
The full solution
The answer panel has leftTriangle and pyramid, prints both shapes 4 rows tall, and tests the negative repeat. Its checks cover the star count, zero rows, the pyramid's padding and width, and the single join. Press Run to see the output.
function leftTriangle(rows) {
const lines = [];
for (let i = 1; i <= rows; i++) lines.push('*'.repeat(i));
return lines;
}
function pyramid(rows) {
const lines = [];
for (let i = 1; i <= rows; i++) {
lines.push(' '.repeat(rows - i) + '*'.repeat(2 * i - 1));
}
return lines;
}
let refused = false;
try {
'*'.repeat(-1);
} catch {
refused = true;
}
console.log(leftTriangle(4).join('\n'));
console.log(pyramid(4).join('\n'));
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('four rows of stars', leftTriangle(4), ['*', '**', '***', '****']);
test('ten stars in a four-row triangle', leftTriangle(4).join('').length, 10);
test('no rows, no output, and no error', leftTriangle(0), []);
test('a pyramid pads the front with spaces', pyramid(3), [' *', ' ***', '*****']);
test('the base is 2n-1 characters wide', pyramid(5)[4].length, 9);
test('every pyramid row holds an odd number of stars', pyramid(6).every((line) => line.trim().length % 2 === 1), true);
test('printing is one join, not a loop', leftTriangle(3).join('\n'), '*\n**\n***');
test('repeat refuses a negative count rather than returning nothing', refused, true);
The classic version of this uses two nested loops and builds each line character by character. repeat replaces the inner loop, which removes the place where the off-by-one usually lives: i runs from 1 to rows and doubles as the star count.
Two details worth keeping. Building an array and joining once is both faster and testable, where console.log inside the loop leaves nothing to assert. And repeat throws a RangeError on a negative count rather than quietly giving '', so a wrong sign shows up immediately instead of printing a blank triangle.
Common mistakes
- Starting the loop at 0. The first row then has no stars, and you need
i + 1everywhere. - Getting the pyramid's star count wrong. It is
2 * i - 1, noti * 2ori + 2: each row adds two stars and stays odd. - Calling
console.loginside the loop. It works on screen but leaves nothing to test. Collect the lines and join them once.
Try it yourself
- Write
rightTriangle(rows), the same triangle but lined up on the right, using spaces in front. - Write
upsideDown(rows)that starts with the widest row and gets smaller. - Make
pyramidtake a second argument for the character to draw, sopyramid(3, '#')uses hashes.