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:

  1. Upper Part: Loops from 1 to size, printing decreasing spaces and increasing stars
  2. 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.

Updated on: 2026-03-15T23:18:59+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements