How to make a multiplication table in JavaScript

How to create a multiplication table in JavaScript, with a code example to get you started.

Creating a Multiplication Table in JavaScript

In this tutorial, we will learn how to create a multiplication table using JavaScript. We will use a for loop to generate the table, and we will also add some HTML formatting to make the table look better. Let's get started.

Step 1: Set up the HTML

First, we will set up the HTML structure of the table. We will use the <table> tag to create the table and the <tr> and <td> tags to define the rows and columns of the table.


<table>
  <tr>
    <td></td>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    ...
  </tr>
  <tr>
    <td>1</td>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    ...
  </tr>
  <tr>
    <td>2</td>
    <td>2</td>
    <td>4</td>
    <td>6</td>
    ...
  </tr>
  ...
</table>

Step 2: Create the JavaScript Code

Now, we will write the JavaScript code that will generate the multiplication table. We will use a for loop to generate the rows and columns of the table. We will also use the document.write() method to insert the HTML tags into the page.


// Set the table size
var tableSize = 10;

// Generate the table
document.write('<table>');

// Generate the rows
for (var i = 1; i <= tableSize; i++) {
  document.write('<tr>');

  // Generate the columns
  for (var j = 1; j <= tableSize; j++) {
    document.write('<td>' + (i * j) + '</td>');
  }

  document.write('</tr>');
}

document.write('</table>');

Step 3: Add Some Styling

Finally, we will add some styling to make the table look better. We will add some padding to the cells, add a border around the table, and set the font size.


table {
  font-size: 14px;
  border: 1px solid #ccc;
}

td {
  padding: 5px;
  border: 1px solid #ccc;
}

And that's it! Now you have a working multiplication table created with JavaScript and HTML. I hope you found this tutorial helpful!

Answers (0)