What Is a Star Pattern in JavaScript?
A star pattern in JavaScript is a program that prints stars (*) in a specific shape using loops and conditions.
These shapes may include:
- Triangles
- Pyramids
- Diamonds
- Squares
- Reverse patterns
Each pattern is formed by controlling:
- Number of rows
- Number of stars
- Number of spaces
Star patterns are usually printed using console.log() in JavaScript.
Why Learn JavaScript Star Pattern Programs?
Learning JavaScript star pattern programs is important because:
- It improves logical thinking
- It helps understand nested loops
- It strengthens problem-solving skills
- It prepares for interviews
- It improves control over output formatting
Star patterns also make beginners comfortable with repetition and conditions in programming.
Basic Structure of Star Pattern Using JavaScript
Most star pattern using JavaScript programs follow this structure:
- Outer loop → Controls rows
- Inner loop → Controls stars/spaces
- String variable → Stores each row
- Print statement → Displays output
Basic template:
for (let i = 1; i <= n; i++) {
let pattern = "";
for (let j = 1; j <= i; j++) {
pattern += "* ";
}
console.log(pattern);
}
Here:
- i controls rows
- j controls stars
- pattern builds each line
Basic Star Patterns in JavaScript
Before diving into complex shapes, it’s important to master the basic star pattern in JavaScript. The most common beginner-friendly patterns are left-aligned and right-aligned triangles. These patterns help you practice using nested for loops and understanding row/column relationships.
Left-Aligned Triangle Star Pattern
This is the simplest star pattern program in JavaScript. Each row contains an increasing number of stars, aligned to the left.
Pattern:
*
**
***
****
*****
Code:
let n = 5;
for (let i = 1; i <= n; i++) {
let row = '';
for (let j = 1; j <= i; j++) {
row += '*';
}
console.log(row);
}
Explanation:
- The outer loop (i) runs from 1 to n (number of rows).
- The inner loop (j) prints stars equal to the current row number.
Right-Aligned Triangle Star Pattern
This pattern aligns the stars to the right, using spaces to shift the stars over.
Pattern:
*
**
***
****
*****
Code:
let n = 5;
for (let i = 1; i <= n; i++) {
let row = '';
// Print spaces
for (let j = 1; j <= n - i; j++) {
row += ' ';
}
// Print stars
for (let k = 1; k <= i; k++) {
row += '*';
}
console.log(row);
}
Explanation:
- The first inner loop prints spaces to shift the stars to the right.
- The second inner loop prints the stars.
Summary:
Mastering these basic star patterns lays the groundwork for more advanced pattern program in JavaScript using for loop. Practice these until you’re comfortable before moving on to pyramids, diamonds, and other complex shapes.
Diamond and Complex Star Patterns in JavaScript
Once you’re comfortable with basic star pattern programs, you can challenge yourself with more advanced and symmetrical designs. Diamond patterns are a classic example, requiring careful use of nested loops to manage both spaces and stars for each row.
Diamond Star Pattern
A diamond pattern is symmetrical and consists of an upper and a lower part. Here’s how you can create a diamond star pattern in JavaScript:
Pattern:
*
***
*****
***
*
Code:
let n = 3; // Number of rows in the upper half
// Upper part of the diamond
for (let i = 1; i <= n; i++) {
let row = '';
// Print spaces
for (let j = 1; j <= n - i; j++) {
row += ' ';
}
// Print stars
for (let k = 1; k <= 2 * i - 1; k++) {
row += '*';
}
console.log(row);
}
// Lower part of the diamond
for (let i = n - 1; i >= 1; i--) {
let row = '';
// Print spaces
for (let j = 1; j <= n - i; j++) {
row += ' ';
}
// Print stars
for (let k = 1; k <= 2 * i - 1; k++) {
row += '*';
}
console.log(row);
}
Explanation:
- The upper part increases the number of stars while decreasing spaces.
- The lower part decreases the number of stars and increases spaces, creating symmetry.
Hollow Diamond Star Pattern
You can also create a hollow diamond by printing stars only at the borders:
Pattern:
*
* *
* *
* *
*
Code:
let n = 3; // Number of rows in the upper half
// Upper half
for (let i = 1; i <= n; i++) {
let row = '';
// Print spaces
for (let j = 1; j <= n - i; j++) {
row += ' ';
}
// Print stars and spaces
for (let k = 1; k <= 2 * i - 1; k++) {
if (k === 1 || k === 2 * i - 1) {
row += '*';
} else {
row += ' ';
}
}
console.log(row);
}
// Lower half
for (let i = n - 1; i >= 1; i--) {
let row = '';
// Print spaces
for (let j = 1; j <= n - i; j++) {
row += ' ';
}
// Print stars and spaces
for (let k = 1; k <= 2 * i - 1; k++) {
if (k === 1 || k === 2 * i - 1) {
row += '*';
} else {
row += ' ';
}
}
console.log(row);
}
Other Complex Patterns
You can use similar logic to create other symmetrical or intricate patterns, such as hourglass shapes, X-patterns, or zig-zags. The key is to carefully analyze the pattern, break it into rows and columns, and use nested loops to control the placement of stars and spaces.
Tips for Complex Patterns:
- Always sketch the pattern and count the number of spaces and stars for each row.
- Use nested loops: one for rows, one for spaces, and one for stars.
- Start with a simple version, then add conditions for hollow or more complex shapes.
Summary:
Mastering diamond and other complex star patterns in JavaScript will deepen your understanding of nested loops and output formatting. These patterns are excellent exercises for refining your logic-building skills and preparing for advanced programming challenges.
Pattern Program in JavaScript Using For Loop
Most star pattern programs in JavaScript are created using nested for loops. One loop controls the number of rows, while the other controls how many stars or spaces are printed in each row.
This structure is the foundation of every pattern program in JavaScript using for loop.
1. Right Triangle Star Pattern
A right triangle star pattern forms a left-aligned triangle where stars increase in each row. It is the easiest pattern and helps beginners understand nested loops.
Pattern Example (n = 5)
*
* *
* * *
* * * *
* * * * *
How It Works
- The pattern has n rows.
- Each row prints stars equal to the row number.
- No spaces are required before the stars.
Code Example
let n = 5;
for (let i = 1; i <= n; i++) {
let row = "";
for (let j = 1; j <= i; j++) {
row += "* ";
}
console.log(row);
}
Explanation
In this program, the outer loop runs from 1 to n and controls how many rows will be printed. For each row, an empty string called row is created to store the stars. The inner loop runs from 1 to i, which means it prints stars equal to the current row number. Each time the inner loop runs, "* " is added to the row string. After the inner loop finishes, the completed row is printed using console.log(). As i increases, more stars are added, forming a growing triangle.
2. Reverse Right Triangle Star Pattern
This pattern is the opposite of the right triangle. Stars decrease in each row.
Pattern Example (n = 5)
* * * * *
* * * *
* * *
* *
*
How It Works
- Starts with n stars.
- Each next row prints one fewer star.
- No spaces are used.
Code Example
let n = 5;
for (let i = n; i >= 1; i--) {
let row = "";
for (let j = 1; j <= i; j++) {
row += "* ";
}
console.log(row);
}
Explanation
Here, the outer loop starts from n and decreases to 1. This means the first row has the maximum number of stars, and each subsequent row has fewer stars. Inside the outer loop, a string variable row is used to store stars. The inner loop runs up to i, so when i becomes smaller, fewer stars are printed. Each iteration adds "* " to the row. Finally, the row is printed. This creates a triangle that shrinks from top to bottom.
3. Square Star Pattern
A square star pattern prints the same number of stars in every row.
Pattern Example (n = 5)
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
How It Works
- Number of rows = number of columns.
- Every row prints n stars.
- No variation in size.
Code Example
let n = 5;
for (let i = 1; i <= n; i++) {
let row = "";
for (let j = 1; j <= n; j++) {
row += "* ";
}
console.log(row);
}
Explanation
In this program, both the outer and inner loops run from 1 to n. This means the same number of rows and columns is printed. For each row, a new empty string is created. The inner loop always runs n times, so it adds the same number of stars in every row. Because the number of stars never changes, each row looks identical. When all rows are printed, the output forms a square shape.
4. Pyramid Star Pattern
A pyramid star pattern forms a centered triangle with increasing odd stars.
Pattern Example (n = 5)
*
***
*****
*******
*********
How It Works
Each row contains:
- Spaces for centering.
- Odd number of stars.
Code Example
let n = 5;
for (let i = 1; i <= n; i++) {
let row = "";
// Print spaces
for (let j = 1; j <= n - i; j++) {
row += " ";
}
// Print stars
for (let k = 1; k <= 2 * i - 1; k++) {
row += "*";
}
console.log(row);
}
Explanation
This program uses two inner loops inside the outer loop. The outer loop controls the number of rows. The first inner loop prints spaces for centering the pyramid. It runs n - i times, so spaces decrease as rows increase. The second inner loop prints stars. It runs 2 * i - 1 times, which ensures an odd number of stars in each row. Both spaces and stars are added to the row string. When printed, this creates a centered pyramid shape.
5. Inverted Pyramid Star Pattern
This is the reverse of the pyramid pattern.
Pattern Example (n = 5)
*********
*******
*****
***
*
How It Works
- Starts with maximum stars.
- Stars decrease each row.
- Spaces increase.
Code Example
let n = 5;
for (let i = n; i >= 1; i--) {
let row = "";
// Print spaces
for (let j = 1; j <= n - i; j++) {
row += " ";
}
// Print stars
for (let k = 1; k <= 2 * i - 1; k++) {
row += "*";
}
console.log(row);
}
Explanation
- Outer loop decreases.
- Stars reduce.
- Spaces increase.
6. Diamond Star Pattern
A diamond pattern combines pyramid and inverted pyramid.
Pattern Example (n = 5)
*
***
*****
*******
*********
*******
*****
***
*
How It Works
- Upper part: Pyramid
- Lower part: Inverted pyramid
- Combined to form diamond
Code Example
let n = 5;
// Upper part
for (let i = 1; i <= n; i++) {
let row = "";
// Print spaces
for (let s = 1; s <= n - i; s++) {
row += " ";
}
// Print stars
for (let st = 1; st <= 2 * i - 1; st++) {
row += "*";
}
console.log(row);
}
// Lower part
for (let i = n - 1; i >= 1; i--) {
let row = "";
// Print spaces
for (let s = 1; s <= n - i; s++) {
row += " ";
}
// Print stars
for (let st = 1; st <= 2 * i - 1; st++) {
row += "*";
}
console.log(row);
}
Explanation
The diamond pattern is created by combining two parts. The first part uses a loop to print a normal pyramid. It prints spaces and stars to build the upper half. The second part uses another loop that runs backward to print an inverted pyramid. It follows the same logic of spaces and stars but in reverse order. When both parts are printed one after another, they form a complete diamond shape.
7. Hollow Square Star Pattern
A hollow square prints stars only at borders.
Pattern Example (n = 5)
* * * * *
* *
* *
* *
* * * * *
How It Works
- Border rows are full of stars.
- Middle rows contain stars only at start and end.
- Inside is empty.
Code Example
let n = 5;
for (let i = 1; i <= n; i++) {
let row = "";
for (let j = 1; j <= n; j++) {
if (i === 1 || i === n || j === 1 || j === n) {
row += "* ";
} else {
row += " ";
}
}
console.log(row);
}
Explanation
In this program, the outer loop controls rows and the inner loop controls columns. For each position in the pattern, an if condition checks whether the position is on the border. If the current row is the first or last, or the current column is the first or last, a star is printed. Otherwise, spaces are added. This logic ensures that only the boundary of the square contains stars, while the inside remains empty, creating a hollow effect.
Summary:
All these programs follow the same basic idea. The outer loop decides how many rows are printed. The inner loops decide how many spaces and stars appear in each row. A string is used to build each row before printing it. By carefully controlling loop limits and conditions, different shapes are formed. Understanding this structure helps learners create their own custom patterns easily.
Using While Loop for Star Pattern JavaScript
While for loops are most common for pattern programs, you can achieve the same results using while loops. The logic remains the same: you use an outer loop to control the rows and an inner loop to control the number of stars (or spaces) in each row. This approach helps you practice different looping constructs and understand their similarities.
Example: Right Triangle Star Pattern Using While Loop
This example prints a left-aligned right triangle of stars using while loops.
Pattern Output (n = 5):
*
* *
* * *
* * * *
* * * * *
Code Example
let i = 1;
let n = 5;
while (i <= n) {
let row = "";
let j = 1;
while (j <= i) {
row += "* ";
j++;
}
console.log(row);
i++;
}
Step-by-Step Explanation
- Initialize Counters:
- i is set to 1 and will control the number of rows.
- n is the total number of rows.
- Outer While Loop (i <= n):
- Runs once for each row.
- For each iteration, a new row string is created to store the stars.
- Inner While Loop (j <= i):
- Prints stars for the current row.
- The number of stars in each row equals the row number (i).
- Each time the inner loop runs, j is incremented and a star is added to row.
- Print the Row:
- After the inner loop finishes, the completed row is printed.
- Increment the Row Counter:
- Increase i to move to the next row.
Why Use While Loops?
- Practice: Helps reinforce how loop initialization, condition, and increment work.
- Flexibility: Great for situations where the number of iterations isn’t known in advance.
- Interview Prep: Shows understanding of multiple loop types.
Tips
- Always initialize your loop counters (i, j) before the loop starts.
- Don’t forget to increment your counters inside the loop to avoid infinite loops.
- Reset row variables inside the outer loop.
Summary:
You can use while loops to create any star pattern in JavaScript by adjusting the loop conditions and logic as needed. Practicing with both for and while loops will make you a more versatile programmer.
So far, all the star pattern JavaScript examples have used a fixed value for the number of rows. However, you can make your pattern program in JavaScript more interactive by letting users specify the size of the pattern.
If you’re running your code in a browser, you can use the prompt() function to get user input. In Node.js or other environments, you can use different methods, but here’s a simple example for browsers:
Example:
let n = prompt("Enter the number of rows for the star pattern:");
n = parseInt(n);
// Generate the pattern
for (let i = 1; i <= n; i++) {
let row = '';
for (let j = 1; j <= i; j++) {
row += '*';
}
console.log(row);
}
Explanation:
- The prompt() function displays a dialog box asking the user to enter the number of rows.
- The input is converted to a number using parseInt().
- The rest of the code uses this value to print the desired star pattern.
Tip:
If you’re using Node.js, you can use the readline module to get user input from the terminal.
Summary:
Allowing users to enter the size of the pattern makes your JavaScript star pattern programs more flexible and interactive. Try updating all your pattern examples to use user input for the number of rows.
Time and Space Complexity Analysis
Time Complexity
For both pyramid and inverted pyramid star patterns, you typically use two nested loops:
- The outer loop runs n times (once per row).
- The inner loops (for spaces and stars) together also run up to n times per row.
This means the total number of operations is roughly proportional to n × n, or O(n²).
Example: For a pyramid with 5 rows, the program performs about 25 operations to print all stars and spaces.
Space Complexity
These patterns use only a few simple variables (i, j, row, etc.) and do not require storing the entire pattern in memory—each row is printed immediately after it is built.
Therefore, the space complexity is O(1) (constant space).
Summary:
- Time Complexity: O(n²) (due to nested loops for rows and columns)
- Space Complexity: O(1) (since only a few variables are used, regardless of pattern size)
This efficiency makes star pattern programs ideal for practicing logic and loops without worrying about memory usage.
Common Mistakes in JavaScript Star Pattern Programs
- Forgetting to Reset the Row String:
Not resetting the string variable (e.g., row = "") inside the outer loop causes rows to combine, resulting in incorrect output. - Incorrect Loop Conditions:
Using wrong start or end values in your loops can lead to extra or missing rows, stars, or spaces—especially in patterns that require precise alignment. - Wrong Spacing Logic:
Miscalculating the number of spaces before stars leads to misaligned or skewed patterns. Double-check your formulas for spaces. - Missing console.log():
If you forget to print each row inside the outer loop, your pattern won’t display as intended. - Mixing Spaces and Stars Incorrectly:
Adding the wrong number of spaces or stars, or placing them in the wrong order, can break the symmetry of pyramid and inverted pyramid patterns.
Best Practices for Writing Star Pattern Programs
- Use Clear Variable Names:
Name your variables (row, i, j, etc.) descriptively to make your code easier to read. - Reset the Pattern String in Each Loop:
Always initialize your row string at the start of each outer loop iteration. - Test with Small Values First:
Use small values of n (like 3 or 5) to quickly check if your pattern logic works before trying larger sizes. - Comment Complex Logic:
Add comments to explain tricky parts of your loops, especially when calculating spaces and stars for alignment. - Practice Regularly:
Try writing different patterns and experiment with variations to build confidence with loops and output formatting.
Applications of Star Pattern Programs
Star patterns, especially pyramid and inverted pyramid patterns, are valuable for:
- Interview Practice:
Common questions in coding interviews test your understanding of nested loops and output formatting. - Learning Loops:
These patterns help beginners visualize and master how nested loops work. - Competitive Coding:
Pattern problems are frequent in programming contests and help sharpen your logical thinking. - Logic Building:
Designing patterns develops your ability to break down problems and construct algorithms step by step. - Teaching Beginners:
Star patterns are simple yet effective exercises for introducing programming fundamentals.
Conclusion
Learning how to write a star pattern program in JavaScript is an essential step for every beginner programmer. It teaches how loops, spaces, and conditions work together to produce structured output.
By practicing different JavaScript star pattern programs, learners improve logical thinking, problem-solving ability, and coding confidence. Although these programs are mainly used for learning purposes, they play a crucial role in building strong programming fundamentals.
Mastering star patterns prepares you for more advanced topics in JavaScript and competitive programming.
Key Points to Remember
- Star patterns use nested loops:
Both pyramid and inverted pyramid patterns rely on outer and inner loops to control rows, spaces, and stars. - Spaces are important for alignment:
Correct calculation of spaces is crucial for centering and shaping the pattern properly. - Most patterns follow O(n²) complexity:
Nested loops result in quadratic time complexity for these patterns. - For loops are most commonly used:
For loops are standard, but while loops can achieve the same results. - Regular practice improves mastery:
Practicing different star patterns builds confidence and strengthens your understanding of loops and output formatting.
Frequently Asked Questions
1. What is a star pattern in JavaScript?
A star pattern is a program that prints stars in different shapes—such as pyramids and inverted pyramids—using loops and conditions.
2. Which loop is best for star patterns?
The for loop is most commonly used for star patterns because it is straightforward, easy to read, and ideal for controlling rows and columns.
3. Can we use while loop for star patterns?
Yes, you can use while loops to create star patterns, including pyramid and inverted pyramid shapes. However, for loops are generally more popular due to their simplicity.
4. Why are star patterns important?
Star patterns help you learn and practice loops, develop logical thinking, and prepare for coding interviews, especially with patterns like pyramids that require careful alignment.
5. Are star patterns used in real projects?
Star patterns are mainly for practice and learning purposes. They are rarely used in real-world applications but are excellent for building foundational programming skills.