Square star pattern in JavaScript

Square Star Pattern in JavaScript

If you are looking to create a square star pattern in JavaScript, you can do so using nested for loops. This is a common programming exercise and can help you understand the basics of loop structures and conditional statements in JavaScript.

Method 1: Using Nested Loops

Here is one way to create a square star pattern using JavaScript:


    const size = 5; // Change this to adjust the size of the pattern
    
    for (let i = 0; i < size; i++) {
        let row = '';
        
        for (let j = 0; j < size; j++) {
            row += '* ';
        }
        
        console.log(row);
    }

This code uses two for loops to iterate through each row and column of the pattern. The outer loop iterates through each row, while the inner loop iterates through each column. We use a variable called "row" to build up each row of stars, and then print it to the console using console.log().

If you prefer to display the pattern on a webpage instead of printing it to the console, you can modify the code to output HTML instead:


    const size = 5; // Change this to adjust the size of the pattern
    let pattern = '';
    
    for (let i = 0; i < size; i++) {
        let row = '';
        
        for (let j = 0; j < size; j++) {
            row += '* ';
        }
        
        pattern += '<p>' + row + '</p>';
    }
    
    document.getElementById('pattern').innerHTML = pattern;

In this code, we use a variable called "pattern" to build up the HTML code for the square star pattern. We create a paragraph element for each row of stars, and then set the innerHTML of a div element with ID "pattern" to the final HTML code.

Method 2: Using Repeat() Method

Another way to create a square star pattern using JavaScript is by using the repeat() method. This method returns a new string with a specified number of copies of an existing string. Here's how you can use it:


    const size = 5; // Change this to adjust the size of the pattern
    
    for (let i = 0; i < size; i++) {
        let row = '* '.repeat(size);
        console.log(row);
    }

In this code, we use the repeat() method to create a string with "size" copies of the string "* ". We then print each row to the console using console.log().

If you want to display the pattern on a webpage, you can use the same approach as in Method 1.

Conclusion

Creating a square star pattern in JavaScript is a fun exercise that can help you learn about loop structures and conditional statements. Whether you use nested for loops or the repeat() method, the key is to understand how these constructs work and how you can use them to achieve your desired output.

Feel free to experiment with different sizes and patterns to see what you can come up with!

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe