I created a pyramid using JavaScript and below is the code that I tried so far using for loop:
function showPyramid() {
    var rows = 5;
    var output = '';
    for (var i = 1; i <= rows; i++) { //Outer loop
        for (var j = 1; j <= i; j++) { //Inner loop
            output += '* ';
        }
        console.log(output);
        document.getElementById('result').innerHTML = output;
        output = '';
    }
}
Pretty basic! But I am trying to bind the result with HTML element, say with div as follows:
document.getElementById('result').innerHTML = output;
Instead it shows five stars in a row rather than the format in JS seeing in the console. Anything that I am missing here?
Full Code:
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Pyramid</title>
  <script>
    function showPyramid() {
      var rows = 5;
      var output = '';
      for (var i = 1; i <= rows; i++) {
        for (var j = 1; j <= i; j++) {
          output += '* ';
        }
        console.log(output);
        document.getElementById('result').innerHTML = output;
        output = '';
      }
    }
  </script>
</head>
<body onload="showPyramid();">
  <h1>Pyramid</h1>
  <div id="result"></div>
</body>
Currently, you are resetting the innerHTML at the end of each loop iteration; either use += to append HTML or append all the output together first, then set the innerHTML. Also, you will need to use the <br> tag to create line breaks in HTML.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pyramid</title>
<script>
function showPyramid() {
    var rows = 5;
    var output = '';
    for (var i = 1; i <= rows; i++) {
        for (var j = 1; j <= i; j++) {
            output += '* ';
        }
        output += "<br/>";
    }
    document.getElementById('result').innerHTML += output;
}
</script>
</head>
<body onload="showPyramid();">
<h1>Pyramid</h1>
<div id = "result"></div>
</body>
</html>
const result = document.querySelector("#result");
function generatePyramid(max = 5) {
  result.innerHTML = "";
  const length = 2 * max - 1;
  for (let i = 1; i <= max; i++) {
    let s = "*".repeat(i).split("").join(" ");
    s = s.padStart(
      s.length + Math.floor((length - s.length) / 2)
    ).padEnd(length);
    const div = document.createElement("div");
    div.innerHTML = s.replace(/\s/g, " ");
    result.appendChild(div);
  }
}
// generatePyramid(); // base 5 stars
generatePyramid(11); // base 11 stars
// generatePyramid(21); // base 21 stars
<h1>Pyramid</h1>
<div id="result"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With