A JavaScript star pattern is a console program that prints "*" in rows. The outer for loop chooses the row. The inner loop appends each star with line += "*", then console.log(line) ends that row.
console.log("*") adds a newline, so a star logged inside the inner loop lands on its own line. "*".repeat(n) builds a whole run, and console.log prints it once. "*" + "*" is "**". "*" + 1 is the string "*1", because + concatenates when either side is a string.
Build the row, then log it once.
line += "*" stays on the same string. console.log(line) writes that string and starts the next row. A solid row can skip the inner loop and use "*".repeat(row).
Syntax
JavaScript Syntax
The inner loop runs once per star. Append to line, then log that string after the inner loop.
JS
for (let row = 1; row <= rows; row++) {
let line = "";
for (let col = 1; col <= row; col++)
line += "*"; // same row
console.log(line); // end the row
}
Reference
How JavaScript Prints a Star
Map each part of the console shape to a JavaScript value or call.
Piece
JavaScript
What it does
Star
line += "*"
Appends one star to the row string
Run of stars
"*".repeat(n)
A string of n stars
Indent
" ".repeat(n)
n spaces
Join
"*" + "*"
The string "**"
String +
"*" + 1
The string "*1"
New row
console.log(line)
Writes the row and ends it
Edge only
line += (col === 1 || col === width) ? "*" : " "
A hollow row
Code
JavaScript Examples
Three programs. Each one changes only the JavaScript that chooses how many stars to print, and where the spaces go.
Example 1 — One star per inner-loop pass
Row 1 appends one star. Each later row appends one more, because the inner loop stops at row.
JS
const rows = 5;
for (let row = 1; row <= rows; row++) {
let line = "";
for (let col = 1; col <= row; col++)
line += "*";
console.log(line);
}
Output
*
**
***
****
*****
How It Works
The outer loop walks row from 1 to 5.
line += "*" builds the row without a newline.
console.log(line) writes that string and starts the next row.
Example 2 — Print the whole row with repeat
Count row down from 5. One console.log writes every star and the newline.
The + operator concatenates when either side is a string, so "*" + 1 is "*1". Another star is line += "*", or "*".repeat(n).
line += "*" appends the star to the same string. console.log(line) writes that string and ends the row. Call it once after the inner loop. console.log("*") inside the inner loop puts each star on its own line.
Yes, when the row is a solid run of stars. console.log("*".repeat(row)) writes that row and the newline in one call. Use line += when the row mixes spaces and stars, or when only the edges should be stars.
console.log(" ".repeat(rows - row) + "*".repeat(2 * row - 1)) builds the indent and the stars as one string. console.log adds the newline. Row 1 has one star; each later row adds two.