Skip to content
jshacks.dev
Browser

Build a Calculator in Vanilla JavaScript

Build a calculator in vanilla JavaScript with a pure state reducer, button and keyboard input, decimals, division by zero and floating-point rounding fixes.

8 min read
Summarize in AI
Flat illustration of a browser and a server trading a request and a response, with the JavaScript, Google Chrome, Postman and Swagger logos.

A calculator is a deceptively good exercise. The interface is a grid of buttons, but the interesting part is the logic behind them: what happens when you press an operator twice, when you type a decimal point after an operator, when you press equals repeatedly or divide by zero. Most beginner calculators break on those cases because they mix the arithmetic with the page. This post builds a calculator in vanilla JavaScript around a pure function, reduce, which takes the current state and a button press and returns the next state. The page only translates clicks and key presses into actions and prints the display. You will see how to handle chained operations, decimals, negation and percent, why 0.1 + 0.2 shows a long tail and how to round it away, how to support the keyboard and how to announce results for screen readers. Number behavior is described in the ECMAScript Number type and on MDN.

State, not strings

Represent the calculator with a small object: the text on the display, the stored left operand, the pending operator and a flag that says the next digit should start a new number.

state.jsJavaScript
export const initial = {
  display: "0",
  left: null,
  operator: null,
  overwrite: false,
};

export function inputDigit(state, digit) {
  if (state.overwrite || state.display === "0") {
    return { ...state, display: digit, overwrite: false };
  }
  if (state.display.replace(/[-.]/g, "").length >= 12) return state;
  return { ...state, display: state.display + digit };
}

export function inputDecimal(state) {
  if (state.overwrite) return { ...state, display: "0.", overwrite: false };
  if (state.display.includes(".")) return state;
  return { ...state, display: state.display + "." };
}

let s = initial;
s = inputDigit(s, "7");
s = inputDecimal(s);
s = inputDigit(s, "5");
s = inputDecimal(s);
console.log(s.display);
Text
7.5

Digits replace a lone zero, so typing 0 then 7 gives 7, not 07. The second decimal point is ignored because the display already contains one. The length check, 12 digits, keeps the number from overflowing the display. Every function returns a new object and never changes the old one, which makes the logic easy to test: call it with a state and an input, and compare the result.

Arithmetic and the floating-point problem

Computers store JavaScript numbers as 64-bit binary floating-point values, so many decimal fractions cannot be represented exactly. The classic example is that 0.1 + 0.2 is 0.30000000000000004. A calculator that prints that result looks broken.

math.jsJavaScript
const OPERATIONS = {
  "+": (a, b) => a + b,
  "-": (a, b) => a - b,
  "×": (a, b) => a * b,
  "÷": (a, b) => a / b,
};

export function compute(left, operator, right) {
  if (operator === "÷" && right === 0) return NaN;
  const result = OPERATIONS[operator](left, right);
  return Number.parseFloat(result.toPrecision(12));
}

console.log(0.1 + 0.2);
console.log(compute(0.1, "+", 0.2));
console.log(compute(1, "÷", 3));
console.log(compute(5, "÷", 0));
Text
0.30000000000000004
0.3
0.333333333333
NaN

toPrecision(12) rounds the result to 12 significant digits, returning a string, and parseFloat converts it back to a number, which also drops trailing zeros. Twelve digits are well within the roughly 15 to 17 that a double can hold, so the noise at the end is removed while real digits stay. One third becomes 0.333333333333. Dividing by zero in JavaScript gives Infinity, not an error, so the code returns NaN explicitly and the display can show a clear "Error" message.

Operators and chaining

Pressing an operator stores the current display as the left operand. If an operator is already pending and a second number has been typed, compute first, so 2 + 3 + shows 5 before waiting for the next number.

operators.jsJavaScript
import { compute } from "./math.js";
import { initial } from "./state.js";

function format(value) {
  if (Number.isNaN(value)) return "Error";
  return String(value);
}

export function inputOperator(state, operator) {
  const current = Number(state.display);

  if (state.operator && !state.overwrite) {
    const result = compute(state.left, state.operator, current);
    return {
      display: format(result),
      left: Number.isNaN(result) ? null : result,
      operator: Number.isNaN(result) ? null : operator,
      overwrite: true,
    };
  }
  return { ...state, left: current, operator, overwrite: true };
}

export function equals(state) {
  if (!state.operator) return state;
  const result = compute(state.left, state.operator, Number(state.display));
  return { display: format(result), left: null, operator: null, overwrite: true };
}

let s = { ...initial, display: "2" };
s = inputOperator(s, "+");
s = { ...s, display: "3", overwrite: false };
s = inputOperator(s, "×");
console.log(s.display, s.operator);
s = { ...s, display: "4", overwrite: false };
console.log(equals(s).display);
Text
5 ×
20

The check !state.overwrite is what makes pressing two operators in a row replace the first instead of computing: after an operator, overwrite is true, so a second operator just replaces the pending one. The final result is (2 + 3) × 4 = 20, calculated left to right as a basic pocket calculator does, not with operator precedence. That is a design choice; a scientific calculator would parse the whole expression instead.

Negate, percent and clear

The sign, percent and clear buttons act on the display only.

extras.jsJavaScript
export function negate(state) {
  if (state.display === "0" || state.display === "Error") return state;
  const display = state.display.startsWith("-") ? state.display.slice(1) : `-${state.display}`;
  return { ...state, display };
}

export function percent(state) {
  const value = Number(state.display) / 100;
  return { ...state, display: String(Number.parseFloat(value.toPrecision(12))), overwrite: true };
}

export function backspace(state) {
  if (state.overwrite || state.display === "Error") return state;
  const next = state.display.slice(0, -1);
  return { ...state, display: next === "" || next === "-" ? "0" : next };
}

console.log(negate({ display: "42" }).display);
console.log(percent({ display: "50" }).display);
console.log(backspace({ display: "123", overwrite: false }).display);
Text
-42
0.5
12

The Clear button simply returns the initial state. Backspace never deletes a computed result, since overwrite is true after an operation, which matches what people expect. A single reducer can route all of these through one function.

One reducer for every button

Giving every button an action name lets both the mouse and the keyboard use the same code path.

reducer.jsJavaScript
import { initial, inputDigit, inputDecimal } from "./state.js";
import { inputOperator, equals } from "./operators.js";
import { negate, percent, backspace } from "./extras.js";

export function reduce(state, action) {
  if (state.display === "Error" && action.type !== "clear") return state;
  switch (action.type) {
    case "digit": return inputDigit(state, action.value);
    case "decimal": return inputDecimal(state);
    case "operator": return inputOperator(state, action.value);
    case "equals": return equals(state);
    case "negate": return negate(state);
    case "percent": return percent(state);
    case "backspace": return backspace(state);
    case "clear": return initial;
    default: return state;
  }
}

let s = initial;
for (const action of [
  { type: "digit", value: "1" },
  { type: "digit", value: "2" },
  { type: "operator", value: "÷" },
  { type: "digit", value: "0" },
  { type: "equals" },
]) {
  s = reduce(s, action);
}
console.log(s.display);
s = reduce(s, { type: "digit", value: "5" });
console.log(s.display);
s = reduce(s, { type: "clear" });
console.log(s.display);
Text
Error
Error
0

Once the display shows Error, only Clear is accepted, so the user cannot type a number on top of it and continue with a broken value. The sequence is 12 ÷ 0, which computes NaN and shows Error.

The page and the keyboard

The buttons carry data-action and data-value attributes, so one delegated listener handles them all. The keyboard maps keys to the same actions.

index.htmlHTML
<main class="calculator">
  <output id="display" aria-live="polite">0</output>
  <div id="keys">
    <button data-action="clear">C</button>
    <button data-action="negate" aria-label="Plus or minus">±</button>
    <button data-action="percent" aria-label="Percent">%</button>
    <button data-action="operator" data-value="÷" aria-label="Divide">÷</button>
    <button data-action="digit" data-value="7">7</button>
    <button data-action="digit" data-value="8">8</button>
    <button data-action="digit" data-value="9">9</button>
    <button data-action="operator" data-value="×" aria-label="Multiply">×</button>
    <button data-action="digit" data-value="4">4</button>
    <button data-action="digit" data-value="5">5</button>
    <button data-action="digit" data-value="6">6</button>
    <button data-action="operator" data-value="-" aria-label="Subtract">−</button>
    <button data-action="digit" data-value="1">1</button>
    <button data-action="digit" data-value="2">2</button>
    <button data-action="digit" data-value="3">3</button>
    <button data-action="operator" data-value="+" aria-label="Add">+</button>
    <button data-action="digit" data-value="0">0</button>
    <button data-action="decimal" aria-label="Decimal point">.</button>
    <button data-action="backspace" aria-label="Delete">⌫</button>
    <button data-action="equals" aria-label="Equals">=</button>
  </div>
</main>
<script type="module" src="app.js"></script>
app.jsJavaScript
import { reduce } from "./reducer.js";
import { initial } from "./state.js";

let state = initial;
const display = document.querySelector("#display");

function dispatch(action) {
  state = reduce(state, action);
  display.textContent = state.display;
}

document.querySelector("#keys").addEventListener("click", (event) => {
  const button = event.target.closest("button");
  if (!button) return;
  dispatch({ type: button.dataset.action, value: button.dataset.value });
});

const KEYS = { "+": "+", "-": "-", "*": "×", "/": "÷" };

document.addEventListener("keydown", (event) => {
  if (event.ctrlKey || event.metaKey || event.altKey) return;
  if (/^\d$/.test(event.key)) dispatch({ type: "digit", value: event.key });
  else if (event.key === ".") dispatch({ type: "decimal" });
  else if (KEYS[event.key]) { event.preventDefault(); dispatch({ type: "operator", value: KEYS[event.key] }); }
  else if (event.key === "Enter" || event.key === "=") { event.preventDefault(); dispatch({ type: "equals" }); }
  else if (event.key === "Backspace") dispatch({ type: "backspace" });
  else if (event.key === "Escape") dispatch({ type: "clear" });
});
Text
(clicking 7, ×, 6, = shows 42; typing the same keys on the keyboard gives the same result)

Every button has an accessible name: the symbols ÷ and − are read inconsistently by screen readers, so aria-label gives them plain words. The display is an <output> element with aria-live="polite", which announces results. The / key is intercepted with preventDefault() because some browsers use it for quick find.

Practical notes

Test the reducer with a table of sequences and expected displays: 1 + 2 = is 3, 5 - 8 = is -3, 0.1 + 0.2 = is 0.3, 9 ÷ 0 = is Error, 2 + 3 × 4 = is 20 under the left-to-right rule. A table of cases catches regressions that clicking cannot. Decide on behaviors you want and write them down: what happens when you press equals twice, whether percent works relative to the left operand and whether the display shows thousands separators. Many pocket calculators repeat the last operation on a second equals, and adding that means remembering the last operator and operand in the state.

For money, do not use floating point at all. Count in whole cents, or use a decimal library, because rounding a double to 12 digits hides the problem rather than solving it. A calculator for learning arithmetic can accept the small noise; an invoice cannot.

Testing the calculator

A reducer is easy to test, so write the tests as a table. Each row is a list of button presses and the display you expect. Cover the plain cases first: 1 2 + 3 = gives 15, 9 - 4 = gives 5. Then the awkward ones that real users find within a minute: pressing an operator twice (5 + × 3 = should use the last operator and give 15), pressing equals with nothing pending, typing a decimal point first (. 5 should show 0.5), typing more than twelve digits, negating zero, backspacing down to a single digit and pressing digits after an error.

Run the table in a loop and report the failing sequence, so a failure tells you exactly which presses broke. When you find a bug in the browser, add its sequence to the table before fixing it, so it cannot come back. For the interface, check the keyboard thoroughly: the keys should do the same thing as the buttons, Enter should not also activate a focused button twice, and the page should not scroll or trigger find when you press the slash key.

Last, check the layout on a small phone screen and with large text enabled. A calculator with tiny buttons is hard to use, and a display that overflows hides the number the user is trying to read. Make the display scroll or shrink its font, and keep the buttons at least 44 pixels square.

Share

Keep reading

Flat illustration of a browser and a server trading a request and a response, with the Google Chrome, Swagger, Postman and NGINX logos.
Browser

The DOM Tree: Nodes, Elements and Text

Understand the DOM tree: node types, the difference between nodes and elements, text and comment nodes, tree navigation properties and how whitespace shows up.

6 min read
Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.