Thuta Learning
JavaScript
ProjectsProgrammingBeginner

Calculator App

JavaScriptLesson 4545 min

What you'll walk away with

  • Model a calculator's state with four fields: display, previous, operator and waiting
  • Write every button as a pure function shaped (state, key) => newState
  • Compute with an operator map instead of eval and handle division by zero, decimals and floating-point noise
  • Test the logic in Node with key-sequence strings before wiring it to the DOM

Explain it simply

Explain it simply

Look at a pocket calculator. The screen shows a single number, but inside it remembers more: the number you typed before, the operator you pressed, and whether the next digit should start a fresh number. That memory is called state.

Each button press makes the calculator look at the old state and produce a new one. In this project you write that "look and produce" step as small functions. The screen and the buttons, the DOM, are only a thin outer layer that you attach at the very end.

Problem → Why → Solution

The problem: everything mixed into a click handler with eval

A common tutorial calculator appends each button's text to a display string and, on =, hands the whole string to eval(). It seems to work until the user presses + twice: "2++2" throws a SyntaxError and the app breaks. In a classic script "010+1" gives 9 because 010 is read as an old octal literal, and "0.1+0.2" shows 0.30000000000000004.

Because all the logic sits inside the click handler, testing any of these cases means opening a browser and clicking by hand. Sites with a strict Content Security Policy often block eval altogether.

calculator-eval.js
const display = document.querySelector("#display");

document.querySelectorAll("button").forEach((btn) => {
  btn.addEventListener("click", () => {
    if (btn.textContent === "=") {
      // "2++2" -> SyntaxError, "010+1" -> 9, "0.1+0.2" -> 0.30000000000000004
      display.textContent = eval(display.textContent);
    } else {
      display.textContent += btn.textContent;
    }
  });
});

Why does this happen?

eval reads the calculator's input as full JavaScript code, so it drags in every quirk of the JavaScript grammar and places no limit on which operators are allowed. In this design the only state is the string on screen, and the logic is glued to the DOM, so nothing can be checked without a browser. Modelling the state explicitly and implementing each operator yourself fixes all of this.

Core concept: the calculator as a state machine

A state machine follows one rule: current state plus one input gives the next state. This calculator needs only four fields. display is the text on screen, previous is the number entered before the operator, operator is the pending operation, and waiting says whether the next digit should start a new number.

KeyWhat changes in the state
0-9Appends to display, or starts fresh when waiting
.Adds a dot only if display has none yet
+ - * /Stores previous, remembers operator, sets waiting
=Combines previous and display, shows the result
CBack to the initial state

Every function leaves the old state untouched and returns a new object built with { ...state, display: ... }. You can log the state after any step, and undo would just mean keeping old states in an array. Because the functions never touch the DOM, you can try them in Node straight away.

For the arithmetic, an OPERATIONS map replaces eval. The key looks up an arrow function, so an operator that is not in the map can never run. The policy decisions are written plainly in code: dividing by zero shows "Error", results are rounded to ten decimal places so floating-point noise never reaches the screen, and 2 + 3 * 4 is evaluated left to right like a basic pocket calculator, giving 20 rather than the precedence answer 14.

Pure function
A function whose output depends only on its input and that has no side effects: it does not touch the DOM, change globals or print to the console. Call inputDigit(state, "7") as often as you like with the same state and you get the same result, which is exactly what lets a test run again and again and be trusted. The whole design of this project rests on that property.
Mental model: one key, one state step
  1. Start from one state object
  2. Send a key to press()
  3. press() returns a new state
  4. The UI only shows state.display

The UI calculates nothing. When you find a bug, reproduce it in Node with a key-sequence string and fix it there.

General pattern

javascript
const ACTIONS = { "+": (a, b) => a + b /* ...one entry per operator */ };

const initialState = () => ({ /* every field the UI needs */ });

function handleInput(state, input) {
  // decide which transition applies, then return a NEW object
  return { ...state, changedField: newValue };
}

let current = initialState();
current = handleInput(current, someInput); // the UI only stores and renders

Keep the state in one object and handle each input with a function that returns a new state. Operators live in a map, so only the allowed ones can ever run.

Run the calculator logic in Node

There is no document and no button anywhere in this file. The run() helper feeds a string such as "10+5=" into press() one character at a time and returns the final display, so one line simulates a whole series of clicks. Watch how "1..5*2=" deals with the dot pressed twice.

calculator-logic.js
// calculator-logic.js - pure functions only, no DOM
const OPERATIONS = {
  "+": (a, b) => a + b,
  "-": (a, b) => a - b,
  "*": (a, b) => a * b,
  "/": (a, b) => (b === 0 ? null : a / b), // null signals an error
};

function createCalculator() {
  return { display: "0", previous: null, operator: null, waiting: false };
}

function inputDigit(state, digit) {
  if (state.waiting || state.display === "0") {
    return { ...state, display: digit, waiting: false };
  }
  return { ...state, display: state.display + digit };
}

function inputDecimal(state) {
  if (state.waiting) return { ...state, display: "0.", waiting: false };
  if (state.display.includes(".")) return state; // only one dot allowed
  return { ...state, display: state.display + "." };
}

function evaluate(state) {
  if (state.operator === null) return state;
  const result = OPERATIONS[state.operator](state.previous, Number(state.display));
  if (result === null) return { ...createCalculator(), display: "Error", waiting: true };
  const rounded = Math.round(result * 1e10) / 1e10; // hide 0.30000000000000004
  return { display: String(rounded), previous: null, operator: null, waiting: true };
}

function chooseOperator(state, operator) {
  if (state.display === "Error") return state;
  // 2 + 3 * : finish the pending 2 + 3 before starting the next operation
  const base = state.operator && !state.waiting ? evaluate(state) : state;
  if (base.display === "Error") return base;
  return { ...base, previous: Number(base.display), operator, waiting: true };
}

function press(state, key) {
  if (/^[0-9]$/.test(key)) return inputDigit(state, key);
  if (key === ".") return inputDecimal(state);
  if (key in OPERATIONS) return chooseOperator(state, key);
  if (key === "=") return evaluate(state);
  if (key === "C") return createCalculator();
  return state; // unknown keys change nothing
}

// Simulate a user pressing buttons, one character per key
function run(keys) {
  return [...keys].reduce(press, createCalculator()).display;
}

console.log(run("10+5="));
console.log(run("0.1+0.2="));
console.log(run("2+3*4="));
console.log(run("8/0="));
console.log(run("1..5*2="));
console.log(run("9C4"));

Code breakdown

  1. Operator map instead of eval"/": (a, b) => (b === 0 ? null : a / b), // null signals an error

    Each operator is an arrow function. Dividing by zero returns null instead of Infinity, and evaluate() turns that into "Error".

  2. The waiting flagif (state.waiting || state.display === "0") {

    After an operator or =, waiting is true, so the next digit starts a new number instead of extending the old one. That is also why a leading "0" is replaced rather than kept.

  3. One dot onlyif (state.display.includes(".")) return state; // only one dot allowed

    If a dot is already there, the same state comes back unchanged, so "1..5" is read as 1.5 and times 2 gives 3.

  4. Rounding the resultconst rounded = Math.round(result * 1e10) / 1e10; // hide 0.30000000000000004

    Binary floating point computes 0.1 + 0.2 as 0.30000000000000004. Rounding to ten decimal places shows 0.3 instead.

  5. Chaining operatorsconst base = state.operator && !state.waiting ? evaluate(state) : state;

    Pressing a second operator while one is pending finishes the first calculation. In "2+3*4=", pressing * produces 5 first, and then 5 * 4 gives 20.

  6. Replaying key pressesreturn [...keys].reduce(press, createCalculator()).display;

    The string is spread into characters, and reduce threads the state through press() one key at a time. This one line is what makes the logic easy to test.

You should see
15
0.3
20
Error
3
4
How one key flows through the code
  1. A key arrives from a click or the keyboard
  2. press(state, key) picks the right function
  3. That function returns a new state object
  4. The UI sets display.textContent = state.display

Known key

state changes and the screen re-renders

Unknown key

the same state comes back; nothing changes

Wiring the logic to the DOM

Add export in front of createCalculator and press in the logic file, and the browser code becomes very short. In the HTML below, each button carries its key in a data-key attribute, and a single listener on the container handles them all (event delegation). The keyboard maps Enter to = and Escape to C, and preventDefault() stops Enter from also clicking whichever button has focus. Both listeners just pass the key to press() and call render().

index.html
<output id="display" aria-live="polite">0</output>
<div id="keys">
  <button data-key="7">7</button> <button data-key="8">8</button>
  <button data-key="+" aria-label="plus">+</button>
  <button data-key="=" aria-label="equals">=</button>
  <button data-key="C" aria-label="clear">C</button>
</div>

<script type="module">
  import { createCalculator, press } from "./calculator-logic.js";

  let state = createCalculator();
  const display = document.querySelector("#display");
  const render = () => { display.textContent = state.display; };

  document.querySelector("#keys").addEventListener("click", (event) => {
    const button = event.target.closest("button[data-key]");
    if (!button) return;
    state = press(state, button.dataset.key);
    render();
  });

  document.addEventListener("keydown", (event) => {
    const aliases = { Enter: "=", Escape: "C" };
    if (event.key === "Enter") event.preventDefault(); // no extra button click
    state = press(state, aliases[event.key] ?? event.key);
    render();
  });
</script>

Do not forget accessibility

<output aria-live="polite"> makes screen readers announce each new result. Give symbol buttons such as + and = an aria-label, and use real button elements instead of divs so Tab and Enter work without extra code.

In real projects

In real projects

Keeping logic in pure functions behind a thin UI reaches far beyond calculators. Checkout forms, multi-step wizards and games are built as state machines, and React's useReducer and Redux reducers follow the very same (state, action) => newState shape. Libraries such as XState can even draw your state machine as a diagram.

Teams usually test a logic module with table-driven tests: rows such as ["10+5=", "15"] and ["8/0=", "Error"] collected in an array and run in one loop. Every new bug report becomes one more row, so if that bug ever returns, the test catches it immediately.

Real money calculations need more than rounding for display. Production apps store amounts as integers, such as cents, or use a decimal library. The rounding in this calculator only tidies what the user sees; it is not suitable for accounting.

Common mistakes

Common mistakes

Passing the display string to eval

eval runs any JavaScript at all. If the input can contain typed or pasted text, arbitrary code can run, and grammar errors like "2++2" crash the app. Implement only the allowed operators yourself, in a map.

Writing the logic inside click handlers

When handlers read and edit display.textContent directly, the only state is the text on screen. Testing needs a browser, and adding keyboard support means copying the logic. Let handlers call press() and render(), nothing more.

Leaving the edge cases undecided

If nobody decides what happens on division by zero, a double dot, or an operator pressed while "Error" is showing, the screen ends up with Infinity, NaN or text like "Error5". Write each decision into the code and add a test row for it.

Mutating the state object

Writing state.display += digit edits the old object, which also changes any states kept for undo, and libraries like React no longer notice the change. Return a new object with { ...state, display }.

Mini challenge

Add backspace, ± and %, then table-test them

Extend the calculator logic with three new keys: < deletes the last digit, ± flips the sign, and % divides the display by 100. Then write a table-driven test from [keys, expected] rows and print PASS or FAIL for each.

  • backspace does nothing while a result (waiting) or Error is shown, and shows "0" once everything is deleted
  • toggleSign leaves "0" alone and flips "12" to "-12" and back
  • percent makes "200*15%=" produce 30
  • press() accepts the new keys and never mutates the old state
  • At least six test rows, ending with an "N/M passed" line
calculator-extra.js
// Start from the lesson's logic (OPERATIONS, createCalculator, press, ...).

function backspace(state) {
  // TODO: ignore while waiting or showing "Error"
  // TODO: drop the last character; "" or "-" becomes "0"
}

function toggleSign(state) {
  // TODO: "0" stays "0"; otherwise add or remove a leading "-"
}

function percent(state) {
  // TODO: display / 100, rounded like evaluate() does
}

// TODO: route "<", "±" and "%" to the new functions inside press()

const cases = [
  ["123<", "12"],
  ["12±", "-12"],
  ["200*15%=", "30"],
  // TODO: add at least three more rows, including an Error case
];

// TODO: run every case, print PASS/FAIL per row, then "N/M passed"

Expected: One line per row, such as PASS 123< -> 12, ending with 8/8 passed.

Show hint

Instead of adding more if statements to press(), route keys through an action map such as { "=": equals, "<": backspace, ... }. For the tests, compare run(keys) === expected and line up the columns with padEnd().

Show solution
calculator-extra.js
// Same core idea as the lesson: (state, key) -> new state, no DOM anywhere
const OPS = {
  "+": (a, b) => a + b,
  "-": (a, b) => a - b,
  "*": (a, b) => a * b,
  "/": (a, b) => (b === 0 ? null : a / b),
};
const fresh = () => ({
  display: "0", previous: null, operator: null, waiting: false,
});
const show = (n) => String(Math.round(n * 1e10) / 1e10);

function backspace(state) {
  if (state.waiting || state.display === "Error") return state; // results are final
  const shorter = state.display.slice(0, -1);
  return { ...state, display: shorter === "" || shorter === "-" ? "0" : shorter };
}

function toggleSign(state) {
  if (state.display === "0" || state.display === "Error") return state;
  const flipped = state.display.startsWith("-")
    ? state.display.slice(1)
    : "-" + state.display;
  return { ...state, display: flipped };
}

function percent(state) {
  if (state.display === "Error") return state;
  return { ...state, display: show(Number(state.display) / 100) };
}

function equals(state) {
  if (!state.operator) return state;
  const value = OPS[state.operator](state.previous, Number(state.display));
  if (value === null) return { ...fresh(), display: "Error", waiting: true };
  return { ...fresh(), display: show(value), waiting: true };
}

function press(state, key) {
  if (key >= "0" && key <= "9") {
    const start = state.waiting || state.display === "0";
    return { ...state, display: start ? key : state.display + key, waiting: false };
  }
  if (key === ".") {
    if (state.waiting) return { ...state, display: "0.", waiting: false };
    if (state.display.includes(".")) return state;
    return { ...state, display: state.display + "." };
  }
  if (key in OPS) {
    if (state.display === "Error") return state;
    const pending = state.operator && !state.waiting ? equals(state) : state;
    if (pending.display === "Error") return pending;
    const previous = Number(pending.display);
    return { ...pending, previous, operator: key, waiting: true };
  }
  const actions = {
    "=": equals, C: fresh, "<": backspace, "±": toggleSign, "%": percent,
  };
  return actions[key] ? actions[key](state) : state;
}

const replay = (keys) => [...keys].reduce(press, fresh()).display;

// Table-driven tests: [keys pressed, expected display]
const cases = [
  ["123<", "12"],
  ["5<<", "0"],
  ["12±", "-12"],
  ["12±±", "12"],
  ["50%", "0.5"],
  ["200*15%=", "30"],
  ["7-9=±", "2"],
  ["9/0=<", "Error"],
];

let passed = 0;
for (const [keys, expected] of cases) {
  const actual = replay(keys);
  const ok = actual === expected;
  if (ok) passed += 1;
  console.log(`${ok ? "PASS" : "FAIL"}  ${keys.padEnd(10)} -> ${actual}`);
}
console.log(`${passed}/${cases.length} passed`);

Quick quiz 1 / 3

In the lesson code, what does run("2+3*4=") return?

Quick quiz 2 / 3

What goes wrong if inputDigit() changes return { ...state, display: digit, waiting: false } to state.display = digit; return state;?

Quick quiz 3 / 3

What is the main reason this project uses an OPERATIONS map instead of eval(display)?

What to remember

  • Model the calculator with four state fields: display, previous, operator and waiting
  • Write every key as a pure function that returns a new state and never mutates the old one
  • Use an operator map instead of eval, and decide division by zero, double dots and rounding explicitly
  • Test the logic in Node with key sequences, then attach a thin DOM layer

MDN — JavaScript Guide — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Calculator App | Thuta Learning