Step 5 / 1145%

Step 5

Showing on the Display

15 min

Write the function that turns the state into what's displayed.

Definition

Rendering is the step that turns an application's state into elements visible on the page. Every time the state changes, we "redraw" the screen from it: the state is the source of truth, the display is only its reflection.

Formatting is part of it: it consists of presenting raw data according to the habits of a language or a country, for example 1234.5 displayed as 1,234.5 in English (and 1 234,5 in French). Formatting never changes the data itself: it only changes the way it is shown.

We need a function that turns the state into a display. It will be called after every user action, and it is the only one that writes to the screen.

This choice has a big advantage: all the keys can simply modify the state, without ever worrying about the display. Once the state is up to date, they just call this function, and the screen updates itself, always in the same way.

Imagine the opposite: if each of the twenty keys had to write to the screen itself, the same formatting would have to be repeated twenty times. At the slightest change (changing the separator, adding a history line), we would have to touch twenty places, with a risk of forgetting one each time. With a single function, we fix it once and everything else follows.

The principle: state, then render

The whole calculator relies on a very simple loop, which will repeat on every click for the rest of the project:

  • 1. The user acts: they click a key.
  • 2. The state changes: a function modifies the state object (current number, operator, expression, etc.).
  • 3. The render runs: updateDisplay() rereads the state and rewrites the screen.

This lesson builds step 3. Steps 1 and 2 come with the input of digits and operators. As long as the render doesn't exist, we can't see anything of what is happening, even if the state is perfectly up to date behind the scenes: that is why we start with it.

1. Formatting a number

The state contains "1234.5", but we want to display 1,234.5, with a comma as the thousands separator:

calculator.js (continued)
function formatForDisplay(value) {
  if (value === "Error") return value;
  const parts = value.split(".");
  const integerPart = Number(parts[0]).toLocaleString("en-US");
  return parts.length > 1 ? integerPart + "." + parts[1] : integerPart;
}
  • split(".") separates the integer part from the decimal part. For "1234.5", we get the array ["1234", "5"]; for "1234", an array with a single element.
  • toLocaleString("en-US") adds the thousands separators: 1234567 becomes 1,234,567. The "en-US" code tells the browser which conventions to apply: changing this code would be enough to get another style of separators.
  • We glue the decimal part back on with a period. If the user has just typed the decimal point ("5."), we display 5..
  • The text Error (step 8) is returned as is.

Note that this function never modifies the state: it keeps the plain number text, with no thousands separators, which is essential for calculating, and the formatting is only applied at display time. This separates the value used by the program from its presentation on screen.

Why not format the whole string directly? Because the decimal part must remain intact: if we passed "1.50" to Number, the trailing zero would disappear and the user would no longer see what they typed. By converting only the integer part, we faithfully keep all the digits after the decimal point, zeros included.

Here is the journey of a few values through formatForDisplay:

  • "0": a single piece, the integer part is 0, we display 0.
  • "1234567.89": two pieces, the integer part becomes 1,234,567, we glue .89 back on: 1,234,567.89.
  • "0.50": the integer part is 0, the decimal part "50" is glued back as is: 0.50.
  • "5.": the decimal part is an empty string, but the array does have two elements, so the period is added: 5..

2. Redrawing the screen

Now that we know how to format a number, all that's left is to write the result into the two lines of the display: the bottom line (the current number) and the top line (the calculation in progress).

calculator.js (continued)
function updateDisplay() {
  currentEl.textContent = formatForDisplay(state.current);

  if (state.operator) {
    previousEl.textContent =
      formatForDisplay(state.previous) + " " + SYMBOLS[state.operator];
  } else {
    previousEl.textContent = state.expression;
  }
}
  • The bottom line always displays the current number.
  • The top line displays 12 × when a calculation is in progress, otherwise the expression of the last calculation (12 × 3 =), otherwise nothing.
  • SYMBOLS is a dictionary that translates the internal operator into a readable symbol: the state remembers "*", but the screen shows ×.
  • currentEl and previousEl are the two HTML elements of the display, retrieved at the beginning of the file: we reuse them on every render instead of searching for them in the page.

The function uses textContent to write into the two lines: the text is inserted as is, without being interpreted as HTML. It is also the only one that touches the screen, which means that if there is a display problem, you will always know where to look.

Also observe the if / else structure: the top line has two mutually exclusive uses. As long as an operator is pending, it shows the calculation in progress; otherwise, it shows the expression of the previous calculation. There is never any need to clear it explicitly: if the state says "nothing", the screen displays "nothing".

Call it once at the very bottom of the file, so that the screen displays the 0 on load:

calculator.js (very last line of the file)
updateDisplay();

Without this initial call, the page would open with the HTML content exactly as it was written, without going through the render. With it, the screen is consistent with the starting state from the moment the page loads.

For what comes next

From now on, add each new piece of code before this updateDisplay(); line: it must always remain the last one in the file. This is the rule that will stay with you until the end of the project.

English formatting: comma as thousands separator and period as decimal point.

English formatting: comma as thousands separator and period as decimal point.

Your turn

Temporarily change current: "0" to current: "1234.5" in the state object, then reload the page: the screen should display 1,234.5. Also try previous: "12" with operator: "*": the top line displays 12 ×. Finally try current: "5.": the screen displays 5.. To go further, test current: "1234567.89" then current: "0.50" and check that the trailing zero is indeed kept. Then put the original values back.

Common mistakes to avoid

  • Placing updateDisplay() too early: if the call isn't at the very end of the file, the functions written after it don't exist yet when it runs.
  • Writing to the screen directly elsewhere: if a key modifies textContent itself, the state and the display may stop matching.
  • Forgetting the trailing-period case: without handling "5.", the period would disappear as soon as you type it.
  • Formatting the state instead of the display: if you store "1,234.5" in state.current, JavaScript can no longer use it to calculate: the comma is not understood as part of a number.
  • Forgetting to call the render again: after every change to the state, updateDisplay() must be called, otherwise the screen keeps the old value.

Key takeaways

  • A single function, updateDisplay, writes to the screen from the state.
  • Formatting only changes the display, never the data.
  • The updateDisplay(); call always stays the last line of the file.
  • The loop to remember: the user acts, the state changes, the render redraws the screen.

Checkpoint

With the original values, the screen displays 0 and the top line is empty.

If the screen stays empty or displays an error, open the console with F12 and read the message: it indicates the file and line involved. In particular, check that currentEl, previousEl and SYMBOLS are properly defined earlier in the file, and that updateDisplay(); is indeed the last line.