Skip to content
Devtoolry

Patterns and small projects · intermediate

JavaScript Program to Make a Simple Calculator

Build a simple calculator in JavaScript that reads lines like "12 * 4", picks the operation from an object of functions and reports bad input without eval().

A calculator is a complete little program: it reads input, validates it, chooses an operation and reports errors instead of crashing. An object that maps each operator to a function replaces a long switch, and adding an operator becomes one line.

The program

JavaScript
const operations = {
  "+": (a, b) => a + b,
  "-": (a, b) => a - b,
  "*": (a, b) => a * b,
  "/": (a, b) => {
    if (b === 0) throw new Error("cannot divide by zero");
    return a / b;
  },
};

function calculate(line) {
  const parts = line.trim().split(/\s+/);
  if (parts.length !== 3) throw new Error("write it as: number operator number");
  const [left, symbol, right] = parts;
  const a = Number(left);
  const b = Number(right);
  if (Number.isNaN(a) || Number.isNaN(b)) throw new Error("both sides must be numbers");
  if (!Object.hasOwn(operations, symbol)) throw new Error(`unknown operator ${symbol}`);
  return operations[symbol](a, b);
}

for (const line of stdin.split("\n").filter((l) => l.trim())) {
  try {
    console.log(line, "->", calculate(line));
  } catch (error) {
    console.log(line, "-> Error:", error.message);
  }
}
Input (stdin)
12 * 4
7 / 2
5 / 0
3 ^ 2
hello
Output
12 * 4 -> 48
7 / 2 -> 3.5
5 / 0 -> Error: cannot divide by zero
3 ^ 2 -> Error: unknown operator ^
hello -> Error: write it as: number operator number

How it works

  1. operations maps each symbol to an arrow function; division throws its own error for 0 (JavaScript would otherwise return Infinity).
  2. calculate() splits the line on whitespace and checks there are exactly three parts.
  3. Number() converts both sides, and Number.isNaN() catches text that is not a number.
  4. Object.hasOwn() makes sure the operator is one of ours, not an inherited property such as "toString".
  5. The loop reads every line of stdin; try/catch turns each thrown error into a message so one bad line does not stop the rest.

Watch it run line by line

Follow the line "5 / 0": calculate calls the "/" function, which throws. The visualizer shows the exception step in each frame as the error travels up, and the highlighted line jumps to the catch block.

“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: The classic switch version

A switch statement is easier to read when you are starting out. Remember break, or execution falls through into the next case.

JavaScript
function calc(a, op, b) {
  switch (op) {
    case "+": return a + b;
    case "-": return a - b;
    case "*": return a * b;
    case "/": return b === 0 ? "cannot divide by zero" : a / b;
    default: return "unknown operator";
  }
}
console.log(calc(10, "-", 4), calc(1, "/", 0));
Output
6 cannot divide by zero

Common mistakes

  • Using eval() on the input: it runs any code the user types. (In this compiler it is also blocked by the sandbox's security policy.)
  • Checking operations[symbol] without Object.hasOwn(): "toString" would find a built-in function.
  • Forgetting break in a switch, so a case falls through and returns the wrong result.

Try it yourself

  • Add % and ** to the operations object.
  • Accept input without spaces, such as "12*4".
  • Keep a running total so a line can start with an operator: "+ 5".

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.