Step 8
25 min
Perform the calculation, handle division by zero and wire up the = key.
Definition
A pure function is a function that depends only on its parameters and modifies nothing outside itself: the same inputs always give the same output, with no side effects. For example, calculate(6, "*", 7) always returns 42, no matter what happens elsewhere in the program.
This type of function is easy to test, understand and reuse, because it can be judged solely on what it receives and what it returns. In contrast, a function that reads or modifies a program's state (like equals, further below) depends on the context in which it is called.
The heart of the project. We code the calculation, protect against division by zero, then wire up the = key. Add all of this code before the final updateDisplay(); line.
This lesson is the longest of the project, because it brings together everything that came before: the state, the operators, the formatting and the rendering. So as not to get lost, we move forward in small pieces, each with a single responsibility: calculate, round, read the state, signal an error, and only then wire up the = key. Each function builds on the previous one, and you can test them one by one in the console.
We start with the simplest and safest part: a function that does nothing but arithmetic.
function calculate(a, operator, b) {
switch (operator) {
case "+":
return a + b;
case "-":
return a - b;
case "*":
return a * b;
case "/":
return a / b;
}
}calculate is a pure function : it does not touch the state, it receives two numbers and an operator, and returns the result. You can test it in the console: calculate(6, "*", 7) returns 42.
switch statement compares operator to each case until it finds the right one, then runs the matching return. It is more readable than a long series of if / else if when comparing a single value against several possibilities."+", "-", "*" and "/" are the "technical" symbols stored in the state. The symbols shown on the display (×, ÷) are handled separately, by the SYMBOLS dictionary.case matches and the function returns undefined. This case should never happen, and the rest of the code treats it as an impossible calculation anyway.Another benefit of this separation: if a result is wrong, you know the problem does not come from the display or from the input, but only from one of these four lines.
In JavaScript, 0.1 + 0.2 gives 0.30000000000000004. To avoid this kind of display, we round to 12 significant digits:
function formatResult(number) {
// toPrecision avoids results like 0.1 + 0.2 = 0.30000000000000004
return String(parseFloat(number.toPrecision(12)));
}This behavior is not a JavaScript bug: the computer stores decimal numbers in binary, and some values that are simple in base 10, such as 0.1, have no exact representation in binary. Tiny discrepancies therefore remain, invisible as long as you do not look at enough digits. Rounding to 12 significant digits makes these discrepancies disappear, while keeping a precision that is more than sufficient for a calculator.
toPrecision(12) rounds to 12 significant digits and returns text.parseFloat turns that text back into a number, which removes useless zeros (0.300000000000 becomes 0.3).String turns the whole thing back into text, because current is always text.Here is the journey of 0.1 + 0.2 through these three steps:
0.30000000000000004.toPrecision(12) : we get the text "0.300000000000".parseFloat : we get the number 0.3, without useless zeros.String : we get the text "0.3", ready to be stored in state.current.The two previous functions know nothing about the state. This one makes the connection: it reads the two memorized numbers, calls the calculation, then rounds the result.
function computeResult() {
const a = parseFloat(state.previous);
const b = parseFloat(state.current);
const result = calculate(a, state.operator, b);
// Infinity (division by zero) or NaN: the calculation is impossible
if (!Number.isFinite(result)) return null;
return formatResult(result);
}parseFloat converts the two texts in the state into numbers. This is essential: without it, "2" + "3" would give "23" (a concatenation) and not 5.Infinity (or NaN for 0 ÷ 0). Number.isFinite detects these cases: the calculation is impossible, so we return null.null is a design choice: the function does not decide what to do about the error, it simply signals it. It is up to the caller (equals, then chooseOperator) to react.calculate, this function is not pure: it reads state. It never modifies it, though, which makes it simple to reason about.When a calculation is impossible, we do not let the calculator display Infinity or NaN: we display a clear message and put the state back into a healthy situation.
function hasError() {
return state.current === "Erreur";
}
function showError() {
state.current = "Erreur";
state.previous = null;
state.operator = null;
state.overwrite = true;
state.expression = "";
}After an error, overwrite is true: the first digit typed erases Erreur and we start over from zero.
hasError simply asks the question "are we in an error state?". The error is identified by the displayed text: no extra variable is needed.showError resets previous and operator to null: the calculation in progress is abandoned, and no leftover operation can disturb the next one.formatForDisplay returns the text Erreur as is: this is what lets the display show it without trying to format it as a number.Here at last is the function that orchestrates everything: it checks that a calculation is possible, runs it, then updates the state with the result.
function equals() {
if (hasError() || !state.operator || state.overwrite) return;
const result = computeResult();
if (result === null) {
showError();
return;
}
state.expression =
formatForDisplay(state.previous) +
" " +
SYMBOLS[state.operator] +
" " +
formatForDisplay(state.current) +
" =";
state.current = result;
state.previous = null;
state.operator = null;
state.overwrite = true;
}= right after 12 ×, for example, therefore does nothing.expression memorizes the calculation for the top line: 12 × 3 =. It is built before modifying current and previous, because we still need to know the two original numbers.previous and operator are reset to null. With overwrite set to true, a digit starts a new calculation and an operator continues with the result.Here is the state before and after 12 × 3 =:
previous is "12", operator is "*", current is "3", overwrite is false.current is "36", previous and operator are null, expression is "12 × 3 =", overwrite is true.operator is empty, updateDisplay() shows expression on top and 36 below.On a calculator, 2 + 3 + already displays 5 before the second +. Replace chooseOperator with this version:
function chooseOperator(operator) {
if (hasError()) return;
// Chaining: 2 + 3 + … → we first compute 2 + 3
if (state.operator && !state.overwrite) {
const result = computeResult();
if (result === null) {
showError();
return;
}
state.current = result;
}
state.previous = state.current;
state.operator = operator;
state.overwrite = true;
state.expression = "";
}overwrite is false), we first compute the partial result.12 × then +), overwrite is true: no calculation is run and the operator is simply replaced.hasError function placed at the start prevents choosing an operator while the display shows Erreur: you must first type a digit to start over.Here is how 2 + 3 + 4 = unfolds:
2 +: previous is "2", the operator is "+".3 then the second +: an operator is pending and overwrite is false, so we compute 2 + 3. current becomes "5", then previous takes the value "5".4 then =: equals computes 5 + 4 and displays 9.Good to know
This calculator computes from left to right, without operator precedence: 2 + 3 × 4 gives 20 and not 14, just like on a basic pocket calculator. Handling precedence is a good challenge for the end of the project.
Only one step remains: declaring the equals function in the actions dictionary. The existing listener takes care of the rest: a key carrying data-action="equals" will automatically call the right function.
const actions = {
decimal: appendDecimal,
equals: equals,
};
Your calculator can finally calculate.

Even the error is handled cleanly, without crashing.
parseFloat : the state contains text, and the + operator would stick it together instead of adding it.Number.isFinite : the display would show Infinity or NaN at the first division by zero.formatResult : 0,1 + 0,2 would display a result with a long tail of decimals.expression after modifying the state : previous and operator would already be cleared, and the top line would be wrong.equals: equals in the dictionary : the = key would then be ignored without any message, because the listener skips unknown actions.calculate is a pure function : it does nothing but arithmetic.toPrecision(12) to hide the discrepancies of decimal arithmetic.null, and the caller decides to display Erreur.Checkpoint
Test: 12 × 3 = gives 36. 0,1 + 0,2 = gives 0,3. 2 + 3 + 4 = gives 9. 7 ÷ 0 = gives Erreur, then type 5: the display starts over from 5.
If a key does not react or the display shows an unexpected result, open the console with F12 and read the error message. Also check that all the functions in this lesson are placed before the final updateDisplay(); line.