ES6 Memory: Understanding UI State
A memory game in fresh ES2015, built without a framework, makes visible which states a UI really has, where they should live and who may change them.
ES6 Memory: Understanding UI State
A single memory card has four distinguishable states: hidden, revealed, matched – and locked while two open cards are being compared. Usually exactly two of them end up in the DOM, as CSS classes such as flipped and matched. The third state hides implicitly in a running setTimeout, the fourth follows from the absence of the others. So two of four states are written down nowhere explicitly – and it is exactly these two that produce the bugs you reliably find in small UIs: the third card that can be revealed in the middle of a comparison, and the pair that stays open for good after a hasty double click.
The fact that I only really noticed this ratio – four states, two of them visibly recorded – when I built a game says a lot about how casually we otherwise treat UI state.
A game as a test bench#
ECMAScript 2015 has been final since June. Classes, modules, const and let, arrow functions, template literals – that is all in the standard now, but it still feels unfamiliar, like a foreign language with familiar vocabulary. I did not want to work through the new syntax with slide examples but with something real: small enough for a few evenings, big enough that real state questions come up. A memory game fits exactly into this gap. Sixteen cards, eight pairs, a move counter – no more domain is needed.
The result is on GitHub as es6-memory. Deliberately without a framework: no jQuery, no React. Not out of dogmatism, but because I wanted to know what remains of the state problems when no tool hides them or takes them off your hands. The build is still up to date: jspm resolves the dependencies, SystemJS loads the ES2015 modules, Babel translates the new syntax for browsers that are not there yet – and a small node build bundles everything into a memory.min.js that you can hook into any existing page with a single div. Fitting for the week in which the repository was created: at the beginning of September, Node 4.0 was released, the first version after the reunification with io.js, with a V8 tailwind for part of the new language features. ES2015 is just moving from paper into the tools, and exactly at this moment a project that uses the language in its pure form is worthwhile.
Which states really exist#
The first gain came before the first line of code: listing the states. For a card there are three, not four – that was the first correction to my own picture of the game:
- hidden: the back is visible, the card reacts to clicks
- revealed: the motif is visible, the card waits for the comparison
- matched: the motif stays visible, the card never reacts again
And the fourth state from the introduction? “Locked” is not a card state at all. It is a state of the game: as long as two revealed cards are being compared – and, if they do not match, stay visible briefly so that you can memorize them – no further card may be turned over. Add to that the move counter and the derived question of whether the game is over. This separation between card state and game state does not occur to you as long as you think in CSS classes. It occurs to you immediately when you have to write the state down as a data structure.
flowchart LR H[hidden] -->|flipCard| R[revealed] R -->|second card<br/>matches| M[matched] R -->|no match<br/>after 800 ms| H M --> E[game over<br/>when all matched]
In ES2015, the model reads pleasantly directly. A class for the card, a factory for the game – and for the first time without the usual tangle of prototypes:
// card.js
export class Card {
constructor(id, motif) {
this.id = id;
this.motif = motif;
this.state = 'hidden'; // 'hidden' | 'revealed' | 'matched'
}
}
// game.js
import { Card } from './card.js';
export function createGame(motifs) {
const pairs = motifs.concat(motifs);
const cards = shuffle(pairs).map((motif, id) => new Card(id, motif));
return { cards, locked: false, moves: 0 };
}
That is the complete state of the game: an array of cards, each with a state field, a locked flag, a counter. No data- attribute, no class list, no hidden timeout that carries truth on the side.
Where the state lives – and where it does not#
I know the obvious alternative from enough jQuery codebases of recent years, including my own: the DOM is the state store. Whether a card is revealed is decided by classList.contains('flipped'). How many cards are open is determined by a selector. That works surprisingly long – and then tips over at always the same spot: as soon as timing comes into play, there are moments when the display lags behind the truth. The animation is not finished yet, the class not yet set, the selector counts wrong. The bug is then not deterministic but depends on how fast someone clicks.
The deeper point: a DOM node mixes two things that belong apart – what is the case and how it currently looks. As long as both are identical, you do not notice the difference. It gets interesting exactly when the two diverge, and they do with every setTimeout, every transition, every server round trip. If, on the other hand, the state lives in the model, it is unambiguous at any point in time, regardless of what the browser is currently drawing. And it is testable without a browser: createGame, flipCard twice, an assertion on state – that runs in Node in milliseconds, without any DOM mock.
One transition function instead of scattered toggles#
The second decision follows from the first: if the state lives in one place, it should also be changed in only one place. Not three event handlers that each do a bit of class logic, but a single function that knows all the rules of the game:
// game.js
export function flipCard(game, cardId, onSettled) {
const card = game.cards.find(c => c.id === cardId);
if (game.locked || !card || card.state !== 'hidden') return;
card.state = 'revealed';
const revealed = game.cards.filter(c => c.state === 'revealed');
if (revealed.length < 2) return;
game.locked = true;
game.moves += 1;
const [first, second] = revealed;
const isMatch = first.motif === second.motif;
setTimeout(() => {
first.state = second.state = isMatch ? 'matched' : 'hidden';
game.locked = false;
onSettled();
}, isMatch ? 300 : 800);
}
The first line after the find is the actual payoff of the whole rework. game.locked || card.state !== 'hidden' takes care of both bugs from the introduction in one expression: the third card during the comparison bounces off locked, the double click on the same card off the card state. In the DOM variant, these were two separate symptoms in two places in the code, each with its own workaround. In the model, they are two facets of the same rule: revealing is only allowed when the game is open and the card is hidden.
While writing this function, I noticed something else: it is the place where you talk about the game. When a colleague asked in the review whether a revealed pair should lock in immediately or with a delay, I could point to two lines. The question “Who may change this state?” deserves the same answer in the small as in the large: ideally exactly one function, and it carries a name from the domain language.
Rendering in one direction#
That leaves the third question: how does the state get onto the screen? The answer that proved sustainable while building is almost uncomfortably simple – after every change, the complete board is redrawn:
// render.js
export function render(game, root) {
root.innerHTML = `
<p class="moves">Moves: ${game.moves}</p>
<ul class="board">
${game.cards.map(card => `
<li class="card ${card.state}" data-id="${card.id}">
${card.state === 'hidden' ? '' : card.motif}
</li>`).join('')}
</ul>`;
}
Template literals make this kind of rendering pleasant for the first time. Before ES2015, this meant string concatenation over twenty lines or a template library as a dependency; now it is a multi-line expression with interpolation, right in the language. The wiring for it is a single delegated listener:
// main.js
import { createGame, flipCard } from './game.js';
import { render } from './render.js';
const root = document.querySelector('.memory');
const game = createGame(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']);
const update = () => render(game, root);
root.addEventListener('click', event => {
if (!event.target.classList.contains('card')) return;
flipCard(game, Number(event.target.dataset.id), update);
update();
});
update();
With that, everything flows in one direction: a click is only a message to the transition function, the transition function changes the model, the model is rendered. No handler ever touches the DOM, no renderer ever changes the state.
flowchart LR E[Click event] --> T[flipCard<br/>transition function] T --> S[(Game state<br/>in the model)] S --> R[render] R --> D[DOM] D -. only reports events,<br/>holds no state .-> E
The reflexive objection is: isn’t re-rendering everything wasteful? I measured it instead of believing it. Replacing seventeen elements via innerHTML costs well under a millisecond in Chrome – for an interaction that happens at most twice per second. The limit exists, but it lies far away from sixteen cards: with hundreds of nodes, form focus or scroll positions that do not survive the rebuild, the approach no longer holds. This is exactly the limit React addresses, which is getting a lot of attention with version 0.13 right now: it keeps the principle “state in, display out” and only makes the write path into the DOM smart by computing differences instead of replacing everything. If you have built the memory game by hand, you read the React documentation differently – as an optimization of a model you already understand rather than as magic.
What a framework takes off your hands – and what it does not#
For me, this is the real insight from the project, and it has only marginally to do with ES2015. A framework takes a lot off your hands:
- efficiently updating the DOM when redrawing becomes too expensive
- breaking the UI down into composable, reusable parts
- wiring events, templates and data without homegrown conventions
What no framework takes off your hands are the three questions this small game forced: which states exist at all – and which of them belong to the card, which to the game? Where do they live – in the model or smeared across class lists and timeouts? And who may change them – a named transition function or every handler a little? If you do not answer these questions, you get the same bugs with a framework as without one, just better packaged. Duplicated state between component and DOM looks tidier in JSX than in jQuery, but it remains duplicated state. As an aside: since the summer, a library experiment called Redux has come out of the React community that declares exactly this transition function the central building block – a sign that the idea does not end with the toy example.
What I take away from this#
The game itself is an afternoon’s fun, a prototype with eight motifs and a move counter. The value lies in what it forced. First: list the states before code is written – the inventory alone corrected my picture, because “locked” had been assumed on the wrong level. Second: the state belongs in the model; the DOM is a projection of it and is no good as storage as soon as timing comes into play. Third: one transition function that knows all the rules instead of toggles spread across handlers – that is where reviews happen, where the domain language lives, where two bugs disappear in one guard line. And the new language? ES2015 did not make the whole thing possible, but it made it pleasant: classes for the model, modules for the boundaries, template literals for rendering. Babel and jspm make sure it already runs in real browsers today. I will probably not build the next larger frontend without a framework – but I will know more precisely which part of the work the framework really takes over and which part has to happen in my own head beforehand.
Further reading#
- Repository es6-memory: https://github.com/MikeBild/es6-memory
- MDN: Classes (JavaScript reference): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
- MDN: Template literals: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
- Babel, the JavaScript compiler for ES2015: https://babeljs.io/
The links help you look up the language features – the decision of where state lives and who changes it, they do not make for you.
Revised and translated from German with the help of AI.