JavaScript to Generate Multiplication Table

In this post, we are going to see how to write a simple JavaScript program to generate a Multiplication table. The output will generate something like this,

Multiplication Table

×12345678910
112345678910
22468101214161820
336912151821242730
4481216202428323640
55101520253035404550
66121824303642485460
77142128354249566370
88162432404856647280
99182736455463728190
10102030405060708090100

Let’s see how can we generate a multiplication table using JavaScript and display it on a webpage:

<!DOCTYPE html>
<html>
<head>
  <title>Multiplication Table</title>
</head>
<body>
  <h2>Multiplication Table</h2>
  <table border="1">
    <thead>
      <tr>
        <th>&times;</th>
        <!-- Header row for the table -->
        <script>
          for (let i = 1; i <= 10; i++) {
            document.write('<th>' + i + '</th>');
          }
        </script>
      </tr>
    </thead>
    <tbody>
      <!-- Generate table rows and cells -->
      <script>
        for (let i = 1; i <= 10; i++) {
          document.write('<tr>');
          document.write('<th>' + i + '</th>'); // Leftmost cell in each row

          for (let j = 1; j <= 10; j++) {
            document.write('<td>' + (i * j) + '</td>'); // Multiply and fill cells
          }

          document.write('</tr>');
        }
      </script>
    </tbody>
  </table>
</body>
</html>

Copy and paste this code into an HTML file, and then open the file in a web browser. It will display a multiplication table from 1 to 10. The JavaScript code within the <script> tags generate the table structure and populate it with the multiplication values. The table headers and cells are created dynamically using loops.

Thanks for Reading…

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top