🟨 JavaScript tutorial for beginners · Class 9 · Lesson 15 of 18 · Free
State Management Basics – Keep Your JavaScript App in Sync
⏱ About 35 minutes · ▶ run real JavaScript here — nothing to install · no sign-in
In this lesson you will
- Keep all changing data of an app in one state object
- Change state only through small update functions with rules
- Draw the screen from state with a render() function and save it
In a cricket match, the scoreboard must always show the true score. If the scorer changes the runs in his notebook but forgets the board, the crowd sees the wrong number. Apps have the same problem: the data changes, and the screen must follow. Keeping them in step is called state management.
What is state in a JavaScript app?
State is the data that describes your app RIGHT NOW: the score, the logged-in name, the items in a cart, whether a menu is open.
A simple, strong habit: keep all of it in ONE object called `state`. Then there is one place to look when something seems wrong.
Watch the trace: every ball changes `state`, and the scoreboard line is made from it.
▶const state = { runs: 0, wickets: 0, balls: 0 };23function scoreboard() {4 return `${state.runs}/${state.wickets} (${state.balls} balls)`;5}67state.runs += 4;8state.balls += 1;9console.log(scoreboard());1011state.wickets += 1;12state.balls += 1;13console.log(scoreboard());
No variables yet.
▌✏️ Change this code and run it yourself
4/0 (1 balls)4/1 (2 balls)
💡 Try it: add a six on the next ball and print the scoreboard again.
Why should only a few functions change the state?
If any line of code can change `state`, mistakes sneak in: a ball counted twice, or 11 wickets. So we change state only through small functions, often called actions.
Each action knows the rules. `addRuns` counts the ball too. `wicket` refuses to go past 10. The rest of the code just calls them.
When the score is wrong, you only need to check these few functions.
{ runs: 7, wickets: 1, balls: 3 }
💡 Try it: write a function wide() that adds 1 run but does NOT count a ball.
How do I keep the screen in sync with state in JavaScript?
Here is the golden rule: click → change state → call `render()`. The `render()` function draws the whole screen from the state.
Never read the score back from the page, and never change the page text in ten places. The page is only a picture of the state.
Click the buttons. Every button does the same two things: one action, then render.
📄 HTML of the page (tap to see / edit)
render: India 0/0
💡 Try it: add a "Reset" button that sets runs and wickets to 0 and calls render().
How do I copy objects and arrays in state safely?
Objects and arrays are shared by reference: `const copy = state` does NOT make a copy. Both names point to the same object, so changing one changes "both".
To make a new version, use spread from Lesson 7: `{ ...state, score: 20 }` and `[...state.tasks, "New task"]`. The old state stays as it was — useful for an undo button.
Watch `before` in the trace: with spread it stays untouched.
▶let state = { name: "Asha", tasks: ["Maths sums"] };2const before = state;34state = {5 ...state,6 tasks: [...state.tasks, "Science diagram"]7};89console.log("Before:", before.tasks);10console.log("Now:", state.tasks);11console.log("Same object?", before === state);
No variables yet.
▌✏️ Change this code and run it yourself
Before: ["Maths sums"]Now: ["Maths sums", "Science diagram"]Same object? false
💡 Spread copies only ONE level. That is why we spread tasks too, not just state.
How do I save app state with localStorage?
When you refresh the page, normal variables are lost. In Class 8 Lesson 13 you saved things with `localStorage`. With state management this is easy: save the whole state object after every change.
`JSON.stringify` turns state into text to save; `JSON.parse` turns it back when the page loads. If nothing is saved yet, start with a default state.
Add a few tasks, then press ▶ Run again — your tasks come back.
📄 HTML of the page (tap to see / edit)
Tasks: ["Pack tiffin"]
💡 Your saved tasks stay on this page between runs, so your output may show more tasks than the first run.
How do I make a tiny store that tells everyone when state changes?
Big apps have many parts that need the same state: a header shows the coins, a shop shows the coins too. A store keeps the state and calls every "subscriber" when it changes.
This store uses a closure (Lesson 10): `state` and `listeners` are private, and only `getState`, `setState` and `subscribe` can touch them.
Libraries like Redux and Zustand work on this same idea, just with more features.
Header: 🪙 80Shop: can buy 4 stickers
💡 Try it: subscribe a third listener that prints "Rich!" when coins are 100 or more.
🤔 Predict the output
Think like JavaScript: read the code and choose what it prints. You get the reason straight away.
Question 1. What does this print?
const state = { marks: [80, 90] };
const copy = state;
copy.marks.push(70);
console.log(state.marks.length);Question 2. What does this print?
const state = { score: 10 };
const next = { ...state, score: state.score + 5 };
console.log(state.score, next.score);Question 3. What does this print?
let state = { count: 0 };
function setState(changes) {
state = { ...state, ...changes };
console.log("render", state.count);
}
setState({ count: 1 });
setState({ count: state.count + 2 });🧩 Your challenge
Pocket-money tracker: keep `state = { balance: 500, history: [] }`. Write `earn(reason, amount)` and `spend(item, amount)`. spend must REFUSE when there is not enough money and print "Not enough for Cricket bat". Every successful change adds a line like "-120 Samosa party" to history. Run the given calls and print the final state. Expected end: { balance: 380, history: ["+200 Birthday gift", "-120 Samosa party", "-200 Comics"] } after the bat is refused.
Not enough for Cricket bat
{ balance: 380, history: ["+200 Birthday gift", "-120 Samosa party", "-200 Comics"] }
⚠️ Common mistakes (and how to fix them)
❌ Wrong
const state = { level: 1 };
state = { ...state, level: 2 };
console.log(state.level);TypeError: Assignment to constant variable.
✅ Right
let state = { level: 1 };
state = { ...state, level: 2 };
console.log(state.level);If you replace the whole state object with a new one, the variable must be declared with let, not const.
❌ Wrong
const state = { likes: 0 };
document.querySelector("#like").addEventListener("click", () => {
state.likes += 1;
console.log("state:", state.likes);
});No error, but the page keeps saying "Likes: 0" — the state changes on every click, yet nobody redraws the screen.
✅ Right
const state = { likes: 0 };
const p = document.querySelector("#likes");
function render() {
p.textContent = `Likes: ${state.likes}`;
}
document.querySelector("#like").addEventListener("click", () => {
state.likes += 1;
render();
});
render();
console.log("ready");Every change must be followed by render(), so the page shows the new state.
❌ Wrong
const state = { tasks: ["Homework"] };
const next = { ...state };
next.tasks.push("Football");
console.log("Old:", state.tasks);No error, but the OLD state changes too: it prints Old: ["Homework", "Football"], so an undo button would be broken.
✅ Right
const state = { tasks: ["Homework"] };
const next = { ...state, tasks: [...state.tasks, "Football"] };
console.log("Old:", state.tasks);
console.log("New:", next.tasks);Spread copies one level only; the tasks array is still shared. Make a new array with [...state.tasks, item].
📌 Remember
- State is the data that describes your app right now — keep it in one object.
- Change state only through small action functions that know the rules.
- Golden rule: event → change state → render(); the page is just a picture of the state.
- Make new versions with spread ({ ...state }, [...arr]) — remember it copies one level only.
- Save the state with JSON.stringify + localStorage and load it back with JSON.parse.
Finished the quiz and the challenge?
Questions students ask
What is state management in JavaScript in simple words?
It is a plan for where your app keeps its changing data and how that data may change. A simple plan: one state object, a few functions that change it, and one render() function that draws the page from it.
What is the difference between state and a variable?
State is made of variables — but only the ones that describe what the user sees or what the app remembers. A loop counter is just a variable. The items in a shopping cart are state.
Do I need React or Redux to manage state?
No. Plain JavaScript with a state object and render() works well for small and medium apps. React and Redux use the same ideas — state, actions, render — and they will feel familiar after this lesson.
Why use spread instead of changing state directly?
A new object makes it easy to see what changed, compare old and new, and build undo. Changing directly is fine in small apps, but you must still call render() every time.