×

javascript · level 2 · unit 7 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Keep the data in one object, then it.

As apps grow, the page and your variables can drift apart. The cure is to keep everything the app knows in one place, the state, usually an object, and never change the page directly.

Write one render function that draws the page from the state. Every listener then follows the same two steps: change the state, then call render(). The page cannot fall out of step, because it is always drawn fresh.

Call render() once at the start, too, so the first view comes from the state.

<p id="board"></p>
<button id="home">Home goal</button>
<button id="away">Away goal</button>
const state = { home: 0, away: 0 };
const board = document.querySelector("#board");
function render() {
  board.textContent = `Home ${state.home} - ${state.away} Away`;
}
document.querySelector("#home").addEventListener("click", () => { state.home++; render(); });
document.querySelector("#away").addEventListener("click", () => { state.away++; render(); });
render();

Press run it to bring the page to life.

console

nothing logged yet

To draw a list from state, empty it with replaceChildren(), then append a fresh item for each entry.