DEV Community

Cover image for Code for Heart Pattern using Javascript
Prince
Prince

Posted on

Code for Heart Pattern using Javascript

CODE

let heart = "";
let size = 6;
// Loop to print upper part of the heart
for (let i = size / 2; i <= size; i += 2) {
    for (let j = 1; j < size - i; j += 2) {//spaces on left
        heart += "  "; // Double space for consistent spacing
    }
    for (let j = 1; j <= i; j++) {  //  hearts in middle left
        heart += "❤️ ";
    }
    for (let j = 1; j <= size - i; j++) {//spaces b/w two halves
        heart += "  "; // Double space
    }
    for (let j = 1; j <= i; j++) { //heart in middle right
        heart += "❤️ ";
    }
    heart += "\n";
}
// Loop to print bottom part of the heart
for (let i = size; i >= 1; i--) {
    // Print spaces on the left side
    for (let j = i; j < size; j++) {
        heart += "  "; // Double space
    }
    for (let j = 1; j <= (i * 2) - 1; j++) { //hearts bottom part
        heart += "❤️ ";
    }
    heart += "\n";
}
console.log(heart);

Enter fullscreen mode Exit fullscreen mode

Top comments (0)