Learn JavaScript · lesson 40 of 60 · about 11 minutes
Project: Safe Calculator
Put a calculator on Sam's page that checks each sum, throws clear errors, and never crashes.
What you'll learn
- Validate input and throw clear errors
- Catch errors at the top level
- Report results neatly
A calculator on the page
Sam is adding a small calculator for visitors doing their maths homework. Each sum they type, like 10 / 4, goes to calculate(expr), which splits it into a number, an operator and a number, throws a clear Error if anything is wrong (the wrong shape, a word instead of a number, dividing by zero, an operator it doesn't know), and otherwise works out the answer. The page goes through every sum inside try...catch, so one bad sum gets its own message and the rest are still worked out.
The design
calculate(expr) takes text like "12 / 4":
1. Split it into a left number, an operator and a right number
2. Throw a clear error if anything is wrong
3. Use a switch to do the maths
A loop runs each expression inside try...catch, so one bad line never stops the rest.
The calculator
function calculate(expr) {
const parts = expr.trim().split(/\s+/);
if (parts.length !== 3) throw new Error("Use the form: number op number");
const [a, op, b] = parts;
const x = Number(a);
const y = Number(b);
if (Number.isNaN(x) || Number.isNaN(y)) throw new Error("Not a number");
switch (op) {
case "+": return x + y;
case "-": return x - y;
case "*": return x * y;
case "/":
if (y === 0) throw new Error("Can't divide by zero");
return x / y;
default:
throw new Error(`Unknown operator ${op}`);
}
}
for (const line of ["12 / 4", "7 * six", "5 / 0", "2 ^ 3", "9 - 10"]) {
try {
console.log(`${line} = ${calculate(line)}`);
} catch (err) {
console.log(`${line} → ${err.message}`);
}
}Output
12 / 4 = 3
7 * six → Not a number
5 / 0 → Can't divide by zero
2 ^ 3 → Unknown operator ^
9 - 10 = -1Tip
Use Number.isNaN to check for NaN. NaN is the only value that isn't equal to itself, so x === NaN is always false.
Where the try goes
If the whole loop sits inside one try, the first bad sum jumps straight to catch and the sums after it are never worked out. Putting the try inside the loop gives each sum its own chance: a bad one is reported, and the loop carries on with the next.
One try for each item
const texts = ["4", "x", "6"];
for (const t of texts) {
try {
const n = Number(t);
if (Number.isNaN(n)) throw new Error(`Bad: ${t}`);
console.log(n * 2);
} catch (err) {
console.log(err.message);
}
}Output
8
Bad: x
12Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.