Triangular Multiplication Pattern in JavaScript

What You’ll Learn
How to print a triangle where row i contains multiplication values i×1, i×2, …, i×i.
You’ll also learn how to keep columns aligned using a fixed-width cell approach.
⭐ Pattern Output
For n = 10, the pattern looks like this:
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
8 16 24 32 40 48 56 64
9 18 27 36 45 54 63 72 81
10 20 30 40 50 60 70 80 90 100Complete JavaScript Program
The outer loop controls rows. The inner loop prints the row’s products. We use padStart for clean alignment.
const n = 10;
const cellWidth = 4;
for (let i = 1; i <= n; i++) {
let line = "";
for (let j = 1; j <= i; j++) {
line += String(i * j).padStart(cellWidth, " ");
}
console.log(line.trimStart());
}🧠 How It Works
Choose n
n = 10 prints 10 rows.
Outer loop prints rows
For each row i, we print exactly i products.
Inner loop prints i×j
i * j generates the multiplication value for each column.
Alignment with fixed width
padStart(cellWidth) makes every cell the same width so columns line up.
Triangle of products
Each new row adds one more multiplication value.
Variation — Browser (aligned cells) Version
In the browser, you can align the triangle using fixed-width inline-block cells:
<!DOCTYPE html>
<html>
<body>
<script>
var n = 10;
for (var i = 1; i <= n; i++) {
for (var j = 1; j <= i; j++) {
document.write('<span style="display:inline-block;width:3em;text-align:right">' + (i * j) + '</span>');
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Change
nto print more rows - Print a full table by looping
jfrom 1..n on every row - Use
cellWidth = String(n*n).length + 1to auto-size cells - Add colors (odd/even) in browser mode for better readability
Avoid
- Printing without fixed-width formatting if you need aligned columns
- Using
document.writein real apps (it’s OK for demos) - Forgetting the newline (
<br>) after each row
Key Takeaways
Row i prints values for j = 1..i.
i * j generates multiplication values.
Use fixed widths (padStart / inline-block) for alignment.
This is a classic nested-loop pattern with O(n2) output size.
❓ Frequently Asked Questions
1 to i, so the number of printed products grows by one each row.line string (or array) per row, then call console.log(line) once per row.i from 1..n, and change the inner loop to for (let j = 1; j <= n; j++).Explore More JavaScript Number Patterns!
Try turning this triangle into a full multiplication table, then apply formatting and colors to make it easier to read.
The total number of printed values in this triangle is \(1 + 2 + \dots + n = n(n+1)/2\).
12 people found this page helpful
