Print a multiplication table in JavaScript
Beginner · 3 min read
A multiplication table, like 7 × 1 = 7 up to 7 × 10 = 70, is the kind of thing you learned at school by heart. Writing one in code is a good small exercise, and it teaches a habit that matters in real apps: keep the data and the way it looks on screen separate. Receipts, reports and invoices all work this way.
In this tutorial you will write two functions. table(n) returns the rows of the table as data. formatTable(n) turns those rows into neatly lined-up text. You need to know what a function, an array and an object are. Array.from, map and padStart are explained as we go.
Data first, text second
You could build one long string inside a loop and print it. It would look fine, but the only way to check it would be to compare every space and line. If you return the rows as objects instead, you can check the actual numbers, and change how they look without touching the maths.
Building an array of a given length
Array.from({ length: 3 }, (_, i) => i) makes an array with 3 items. For each position i (0, 1, 2) it calls the function and stores what it returns. The _ is a name for the first argument, which we don't need.
console.log(Array.from({ length: 3 }, (_, i) => i + 1)); // [ 1, 2, 3 ]
Here is the exercise. Try it on your own first if you like, or follow the steps below.
20 Multiplication table for a number
easyProduce the multiplication table for a given number, from 1 up to a limit. Return it in a form that can be checked as well as printed.
Stuck? Three hints, smallest first
- 1. Build an array of rows, then join it for display. Do not build a single string.
- 2.
padStartlines the columns up when the numbers vary in width. - 3. Returning structured data and formatting separately is what makes it testable.
Step 1: return the rows
Each row is an object with the multiplier and the product. Positions start at 0, so add 1 to get 1 to 10.
function table(n, upTo = 10) {
return Array.from({ length: upTo }, (_, i) => ({
multiplier: i + 1,
product: n * (i + 1),
}));
}
console.log(table(7, 3));
// [ { multiplier: 1, product: 7 }, { multiplier: 2, product: 14 }, { multiplier: 3, product: 21 } ]
upTo = 10 is a default value: if you leave it out, you get ten rows. The object is wrapped in brackets, ({ … }), because an arrow function followed by a bare { would treat it as a block of code, not an object.
Step 2: check the data
Because the rows are data, you can pull out just the products and check them:
const seven = table(7);
console.log(seven.length); // 10
console.log(seven.map((r) => r.product)); // [ 7, 14, 21, 28, 35, 42, 49, 56, 63, 70 ]
map makes a new array by running a function on each item. Here it picks the product from each row.
Step 3: turn a row into text
A template literal (text in backticks) drops values in with ${ }.
const row = { multiplier: 3, product: 21 };
console.log(`7 x ${row.multiplier} = ${row.product}`); // 7 x 3 = 21
Step 4: line up the columns
Print all ten rows that way and the equals signs wander, because 7 is one digit and 10 is two. padStart(width) adds spaces to the front of a string until it is width characters long, so short numbers line up with long ones. It works on strings, so convert numbers with String() first.
console.log(String(7).padStart(3)); // " 7", with two spaces in front
console.log(String(70).padStart(3)); // " 70", with one space in front
Step 5: format the whole table
formatTable gets the rows from table, turns each into one line with map, then joins the lines with '\n', which is a line break.
function formatTable(n, upTo = 10) {
return table(n, upTo)
.map((row) => `${String(n).padStart(2)} x ${String(row.multiplier).padStart(2)} = ${String(row.product).padStart(3)}`)
.join('\n');
}
console.log(formatTable(7, 3));
The output is three lined-up rows:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
Notice that formatTable does no multiplying at all. All the maths lives in table. If you later want the table as an HTML list or a spreadsheet, you write another formatter and leave table alone.
The full solution
The complete answer prints the full table for 7, then the first five rows for 12. The checks underneath test the data (row count, products, first and last rows) and one formatted line. Press Run to see the output.
// Return the data...
function table(n, upTo = 10) {
return Array.from({ length: upTo }, (_, i) => ({
multiplier: i + 1,
product: n * (i + 1),
}));
}
// ...and format it separately.
function formatTable(n, upTo = 10) {
return table(n, upTo)
.map((row) => `${String(n).padStart(2)} x ${String(row.multiplier).padStart(2)} = ${String(row.product).padStart(3)}`)
.join('\n');
}
console.log(formatTable(7));
console.log('');
console.log(formatTable(12, 5));
const seven = table(7);
const products = seven.map((r) => r.product);
Output
7 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 7 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('ten rows by default', seven.length, 10);
test('the products', products, [7, 14, 21, 28, 35, 42, 49, 56, 63, 70]);
test('the first row', seven[0], { multiplier: 1, product: 7 });
test('the last row', seven[9], { multiplier: 10, product: 70 });
test('a custom limit', table(12, 5).length, 5);
test('formatting lines up the columns', formatTable(7, 1), ' 7 x 1 = 7');
test('a table of zero is all zeros', table(0, 3).map((r) => r.product), [0, 0, 0]);
Splitting table from formatTable is the habit worth taking from this one. A function that builds a formatted string can only be tested by comparing strings, which breaks the moment you change the spacing. A function that returns data can be asserted on meaning, and the formatting becomes a separate, trivial concern.
Common mistakes
- Building one big string in a loop. It prints fine, but you can't check the numbers without checking every space too.
- Forgetting the
+ 1.Array.frompositions start at 0, so the table would start with 7 × 0. - Writing
(_, i) => { multiplier: … }without the outer brackets. JavaScript reads the braces as a code block and the function returnsundefined.
Try it yourself
- Add a
fromparameter sotable(7, 12, 5)gives 7 × 5 up to 7 × 12. - Write
formatAsList(n)that formats the same rows as "7, 14, 21, …" on one line. - Build a full 10 × 10 grid: an array of ten tables, and a formatter that prints it as a square.