DEV Community

Play Button Pause Button
Prince
Prince

Posted on

Diamond Pattern Printing using javascript

Follow us on instagram for daily coding videos

https://www.instagram.com/webstreet_code/

Introduction

In this video, I’ll show you how to create a colorful diamond pattern using JavaScript. This project is a great way to practice your skills and explore how to manipulate strings and whitespace for alignment in the console.

What You'll Learn

  • How to use loops to create patterns in JavaScript.
  • The importance of string manipulation for formatting output.
  • How to create visually appealing text-based art in the console.

Code Explanation

Here’s the code used to create the diamond pattern:


javascript
function printDiamond(n) {
    let pattern = '';
    const symbol = '💎'; // Diamond symbol

    // Upper part of the diamond
    for (let i = 1; i <= n; i++) {
        pattern += ' '.repeat(n - i); // Add leading spaces
        for (let j = 0; j < 2 * i - 1; j++) {
            pattern += symbol + ' '; // Add diamonds with space
        }
        pattern += '\n'; // Move to next line
    }

    // Lower part of the diamond
    for (let i = n - 1; i >= 1; i--) {
        pattern += ' '.repeat(n - i); // Add leading spaces
        for (let j = 0; j < 2 * i - 1; j++) {
            pattern += symbol + ' '; // Add diamonds with space
        }
        pattern += '\n'; // Move to next line
    }

    console.log(pattern);
}

// Set the number of rows (height of the diamond)
let rows = 5; // You can change the number of rows here
printDiamond(rows);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)