Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Function to create diamond shape given a value in JavaScript?
In JavaScript, you can create a function to generate diamond-shaped patterns using stars and spaces. A diamond shape consists of two parts: an upper triangle that expands and a lower triangle that contracts.
Example
function createDiamondShape(size) {
// Upper part of diamond (including middle)
for (var i = 1; i = i; s--) {
process.stdout.write(" ");
}
// Print stars
for (var j = 1; j
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
How It Works
The function works in two main parts:
-
Upper Part: Loops from 1 to size, printing decreasing spaces and increasing stars
-
Lower Part: Loops from 1 to size-1, printing increasing spaces and decreasing stars
Alternative Implementation
Here's a cleaner version that builds each line as a string:
function createDiamondPattern(size) {
// Upper part including middle
for (let i = 1; i = 1; i--) {
let line = " ".repeat(size - i) + "* ".repeat(i);
console.log(line);
}
}
createDiamondPattern(4);
*
* *
* * *
* * * *
* * *
* *
*
Comparison
| Approach | Readability | Performance | Browser Support |
|---|---|---|---|
| Nested loops | Moderate | Good | All browsers |
| String.repeat() | High | Good | ES6+ required |
Conclusion
Creating diamond patterns in JavaScript involves printing spaces and stars in a calculated pattern. The nested loop approach offers maximum compatibility, while modern string methods provide cleaner code.
Advertisements
