How to print star pattern in JavaScript in a very simple manner?

JavascriptWeb DevelopmentObject Oriented Programming

Here is a simple star pattern that we are required to print inside the JavaScript console. Note that it has to be printed inside the console and not in the output or HTML window −

*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*

Here’s the code for doing so in JavaScript −

Example

const star = "* ";
//where length is no of stars in longest streak
const length = 6;
for(let i = 1; i <= (length*2)-1; i++){
   const k = i <= length ? i : (length*2)-i;
   console.log(star.repeat(k));
}

Output

The console output will be −

*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*

The String repeat() function is way of telling the compiler to produce a string with n copies of the string it is used in context of, where n is the argument it receives.

The time complexity of this code is O(length^2) and the space complexity is O(1).

raja
Published on 18-Aug-2020 07:30:16
Advertisements