Home Programs How to Display a Multiplication Table in JavaScript

How to Display a Multiplication Table in JavaScript

In  this example we will show you how to generate a multiplication table

Example 1

We take the user input and store in the constant number

We then use a for loop to loop from 1 to 10

We then display the multiplication table multiplying the number the user inputted from 1 to 10

// generate a multiplication table
// get user input
const number = parseInt(prompt('Enter an integer: '));

//create the multiplication table
for(let i = 1; i <= 10; i++) 
{
    // multiply i with user number
    const result = i * number;
    // display the result
    console.log(`${number} * ${i} = ${result}`);
}

When you run this you will see something like this, this was with user input of 5

5 * 1 = 5
 5 * 2 = 10
 5 * 3 = 15
 5 * 4 = 20
 5 * 5 = 25
 5 * 6 = 30
 5 * 7 = 35
 5 * 8 = 40
 5 * 9 = 45
 5 * 10 = 50

Example 2

A slight tweak to the above to allow the user to select the range as well

// generate a multiplication table
// take number input from the user
const number = parseInt(prompt('Enter an integer: '));

// get the range from the user
const range = parseInt(prompt('Enter a range: '));

//create a multiplication table
for(let i = 1; i <= range; i++) 
{
    const result = i * number;
    console.log(`${number} * ${i} = ${result}`);
}

You may also like