This tutorial is all about how to create multiplication table in javascript. First, we’ll create it using the for loop, while loop, and do-while loop. At last, we’ll create a small webpage using HTML, CSS, and javascript that will display the table in the browser by the button click.
A multiplication table is a mathematical table that shows the result of multiplying each number from one to ten, inclusive, by every other number from one to ten, inclusive. For example:
3 X 1 = 3
3 X 2 = 6
3 X 3 = 9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 x 7 = 21 and so on…
const number = parseInt(prompt("Enter the number :"));
// Function to Create multiplication table in javascript
function multiplicationTable(number, range=10) {
for (let i=1; i<=range; i++) {
console.log(`${number} X ${i} = ${i*number}`)
}
}
multiplicationTable(number)
Here is the output of the code for number=2:
2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
Most of the code will remain except we will replace the for loop inside the “multiplicationTable” function with the while loop. Here is the code for that.
const number = parseInt(prompt("Enter the number :"));
function multiplicationTable(number, range=10) {
let i = 1;
while (i <= range) {
console.log(`${number} X ${i} = ${i*number}`)
i++;
}
}
multiplicationTable(number)
Similarly, we can achieve the exact output by replacing the while loop with the do while loop. Here is what I mean.
const number = parseInt(prompt("Enter the number :"));
function multiplicationTable(number, range=10) {
let i = 1;
do {
console.log(`${number} X ${i} = ${i*number}`)
i++;
} while (i <= range);
}
multiplicationTable(number)
Let’s create an interactive webpage having a number input box and a button that will display a multiplication table of the number entered by the user in a nice and clean manner. Here is the code for that.
<html>
<head>
<style>
#result {
margin-top: 15px;
width: 10%;
text-align: center;
}
#result td {
border: 1px solid #F7EDDB;
padding: 10px;
}
#result tr:nth-child(odd){background-color: #F7EDDB;}
</style>
</head>
<body>
<input type="number" id="number">
<button id="getTable">Display Table</button>
<table id="result"></table>
<script>
function getTable() {
const range = 10;
const number = document.querySelector("#number").value;
let table = '';
for (let i=1; i<=range; i++) {
table += `<tr><td>${number} x ${i} = ${i*number}</td></tr>`;
}
document.querySelector("#result").innerHTML = table;
}
document.querySelector("#getTable").addEventListener("click", getTable)
</script>
</body>
</html>