Odd Number Triangle in JavaScript

What You’ll Learn
How to print an odd-length number triangle where each row concatenates digits from 1 up to the current odd size.
You’ll practice using nested loops and string/number concatenation in JavaScript.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
123
12345
1234567
123456789Complete JavaScript Program
The outer loop generates odd row lengths. The inner loop concatenates digits from 1 up to that length.
const rows = 5;
// Outer loop picks odd lengths: 1, 3, 5, 7, 9...
for (let i = 1; i <= 2 * rows - 1; i += 2) {
let line = "";
// Inner loop appends digits without spaces.
for (let j = 1; j <= i; j++) {
line += j;
}
console.log(line);
}🧠 How It Works
Set the number of rows
const rows = 5; determines how many odd-length lines we generate.
Outer loop picks odd lengths
for (let i = 1; i <= 2 * rows - 1; i += 2) visits i = 1, 3, 5, 7, 9.
Start a line as empty
let line = ""; prepares an accumulator string for each row.
Inner loop concatenates digits
The inner loop appends j from 1 to i, without adding spaces.
Odd-length concatenation triangle
Each row grows by 2 digits, forming the odd-number triangle shape.
Variation — Browser (document.write) Version
Print the same triangle directly in an HTML page using document.write:
<!DOCTYPE html>
<html>
<body>
<script>
const rows = 5;
for (let i = 1; i <= 2 * rows - 1; i += 2) {
for (let j = 1; j <= i; j++) {
document.write(j);
}
document.write("<br>");
}
</script>
</body>
</html>💡 Tips for Enhancement
Try These
- Increase
rowsto generate longer odd concatenation lines - Add a separator like
' 'if you want spaced output - Build the output using an array and
join('')for cleaner code - Print the pattern in reverse by counting i from large to small
Avoid
- Using
i += 1instead ofi += 2(breaks odd-length rows) - Accidentally resetting
linein the wrong loop scope - Adding spaces or separators inside the inner loop when you need concatenation
- Forgetting the
document.write("<br>")after each row in browser output
Key Takeaways
The outer loop generates odd row lengths (increment by 2).
The inner loop appends digits from 1 to i to form the concatenation.
No spaces are added, so rows like 1234567 appear as continuous text.
You can switch output methods: console.log vs document.write.
❓ Frequently Asked Questions
line using line += j (no separator). In browser mode it calls document.write(j) directly.line += j + ' ' or join with ' ' when using an array.1234567891011 and so on.Explore More JavaScript Number Patterns!
Keep practicing nested loops to build progressive, triangle-shaped output with different rules.
Odd-length digit concatenation is a handy pattern for learning how to convert repeated loops into clean string output.
12 people found this page helpful
