Skip to content
Devtoolry

Patterns and small projects · beginner

JavaScript Program to Display the Multiplication Table

Print the multiplication table of any number in JavaScript with a for loop and padStart() for aligned columns, then a full grid with nested loops.

A multiplication table is a single loop, and a good place to learn alignment: String(value).padStart(3) adds spaces on the left so every number takes three characters and the columns line up.

The program reads the number from the stdin box with prompt(), so put a number there before running it. In this compiler prompt() does not open a dialog: it returns the next line of the stdin box.

The program

JavaScript
const n = Number(prompt());

for (let i = 1; i <= 10; i++) {
  console.log(`${n} x ${String(i).padStart(2)} = ${String(n * i).padStart(3)}`);
}
Input (stdin)
7
Output
7 x  1 =   7
7 x  2 =  14
7 x  3 =  21
7 x  4 =  28
7 x  5 =  35
7 x  6 =  42
7 x  7 =  49
7 x  8 =  56
7 x  9 =  63
7 x 10 =  70

How it works

  1. Number(prompt()) reads 7 from the stdin box and converts it to a number.
  2. The loop runs i from 1 to 10 inclusive.
  3. padStart(2) and padStart(3) right-align the multiplier and the product, so every row has the same width.

Watch it run line by line

Only i changes on each pass while n stays 7, and one row is added to the output per pass.

“Visualize step by step” opens the program in the JavaScript Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.

Another way: A full grid

Two nested loops print the whole table. The inner loop builds one row with map() and join().

JavaScript
for (let row = 1; row <= 5; row++) {
  const cells = [1, 2, 3, 4, 5].map((col) => String(row * col).padStart(4));
  console.log(cells.join(""));
}
Output
   1   2   3   4   5
   2   4   6   8  10
   3   6   9  12  15
   4   8  12  16  20
   5  10  15  20  25

Common mistakes

  • Forgetting Number(): "7" * 2 happens to work (14), but "7" + 1 is "71", so mixing operators gives surprising results.
  • Calling padStart on a number: it is a string method, so convert with String() first.
  • Using i < 10, which stops at 9.
  • Leaving the stdin box empty: prompt() then returns null, Number(null) is 0, and every row prints 0.

Try it yourself

  • Read the upper limit from a second line of input.
  • Extend the grid to 12 × 12 with a header row.

Open the program in the JavaScript Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.

Browse all 25 JavaScript examples, or write your own program in the online JavaScript Compiler.