number pyramid in javascript 1

number pyramid in javascript

// Display pyramid of number using JavaScript
function pyramid(n) {
   for (let i = 1; i <= n; i++) {
      let str = ' '.repeat(n - i);
      let str2 = '*'.repeat(i * 2 - 1);
      console.log(str + str2 + str);
   }
}

pyramid(5);

Here is what the above code is Doing:
1. We have a function called pyramid that takes a number as an argument.
2. We have a for loop that runs from 1 to the number passed to the function.
3. We have a variable called str that is a string of spaces. The number of spaces is equal to the number passed to the function minus the current iteration of the for loop.
4. We have a variable called str2 that is a string of asterisks. The number of asterisks is equal to the current iteration of the for loop times 2 minus 1.
5. We log the str variable, the str2 variable, and the str variable again.

Similar Posts