Unit 6 · JavaScript in the page
State: change the data, then render
Keep the data in a variable, change that, then call a render() that writes the data to the page. The page never updates itself when a variable changes, and it should not be where the data lives.
The mix-up
What people often think
“The screen updates itself, and the variable follows.”
What the tutor says
The screen never changes by itself. Code changes the data first, then writes that data to the page.
How it works
Reading the number back off the screen goes wrong fast: textContent is text, so adding 1 to "0" gives "01".
Order matters. Render before the change and the page shows the old value. Push a task into the array and forget to render, and the array knows about it while the page does not. Change, then render, every time.
An example
let count = 0;
function render() {
counter.textContent = count;
}
button.addEventListener('click', () => {
count = count + 1; // 1. change the data
render(); // 2. show it
});Close cousins of this mix-up
The tutor watches for these in the same lesson.
“Changing the variable updates the screen automatically.”
The variable changed, but nothing told the page. Call render() after every change.
“It does not matter whether you render before or after changing the data.”
Render first and the page shows the old number. Change the data, then render.
“You can add to the number on the screen directly.”
textContent is text, so adding 1 to '0' gives '01'. Change the count variable, then render it.
“Pushing into the array shows the new task.”
The array changed, but the page is a separate thing. Call render() after you push.
“Adding an <li> to the page is enough.”
Then the page knows about the task but your data does not. Push it into todos, and let render() draw the list.
Practise it with a tutor watching
State
Build a counter and a to-do list where the data decides what the screen shows.
Free, no account needed.