Learn it
A web app keeps state (data that changes), renders the UI from that state, and updates when users act. Pattern: event β update state β render.
π§° Tool: a free online editor such as CodePen or JSFiddle, or a plain text editor and your web browser.
Code examples
JavaScript
const state = { count: 0, history: [] };
function render() {
document.querySelector("#count").textContent = state.count;
document.querySelector("#log").textContent = state.history.join(", ");
}
function change(amount) {
state.count += amount;
state.history.push(amount > 0 ? "+" + amount : String(amount));
render();
}
document.querySelector("#plus").addEventListener("click", () => change(1));
document.querySelector("#minus").addEventListener("click", () => change(-1));
render();
HTML: span#count, p#log, buttons #plus and #minus.
Project: State counter
- Build the counter.
- Add an undo button that removes the last history item and reverses it.
- Never edit the DOM outside render().
Challenge: Add a +10 button.