Learning objective: Identify an application's state, keep it in one JavaScript object instead of scattered across the DOM, and change it through small, named update functions.
Skills practised: Application state, State objects and updates.
04Explanation
State is the data your app needs to remember right now: the items in a cart, which tab is open, what the person typed in the search box.
If the truth lives only in the page (reading counts back from text, checking classes to see what is selected), it is easy for parts of the page to disagree.
Instead, keep state in one JavaScript object (const state = { ... }) and treat the page as a picture of it.
Change state only through small, named functions (addItem, setFilter). Then there is one place to look when something goes wrong.
Separate source state (what you must store: the items) from derived values (what you can compute: the total, the visible items). Store the first, compute the second, so they cannot drift.
Updating immutably (state.items = [...state.items, x]) makes changes easy to detect and to undo; mutating in place is fine for small apps if every change still goes through an update function.
A tiny store pattern (getState, update(fn), subscribe(listener)) notifies the UI after every change. Libraries such as Redux formalise this idea.
UI-only state (is the menu open?) can stay inside a component; shared state (the signed-in user, the cart) belongs in the app's store.
05Definitions
Application state
The data an app keeps in memory that decides what it shows and how it behaves.
Source of truth
The single place where a piece of data is stored and from which everything else is derived.
Derived value
A value computed from state, such as a total or a filtered list, rather than stored separately.
Update function
A named function that is the only way a particular part of the state changes.
Store
An object that holds state, applies updates and notifies subscribers about changes.
Application state visualizer. Dispatch actions on a small cart and watch the state object change step by step, with derived values recomputed beside it.
Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.
The total is out of date
Derive instead of storing a copy.
const state = { prices: [5, 10], total: 15 };
function addPrice(p) {
state.prices.push(p);
}
addPrice(20);
console.log("Total:", state.total);
To-do state functions
Write update functions for a list.
const state = { todos: [], nextId: 1 };
function addTodo(text) {
// TODO: push { id, text, done: false } and increase nextId
}
function toggleTodo(id) {
// TODO: flip done for the todo with this id
}
addTodo("Read");
addTodo("Run");
toggleTodo(2);
console.log(JSON.stringify(state.todos));
A store with unsubscribe
Build a small store.
// Write createStore(initial) returning { get, update(fn), subscribe(listener) }.
// update replaces the state with fn(state) and calls every listener with it.
// subscribe returns a function that removes that listener.
09Prediction
Commit to an answer first, then run the real code to compare.
An online shop shows the cart count in the header, a mini cart in a drawer and the full cart on checkout. All three read one cart state and re-render when it changes, so they can never disagree.
Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.
Automated acceptance tests for this lesson
These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.
The total is out of date: Prints Total: 35; Stays correct; No stored total
To-do state functions: Prints the todos; Unknown ids are ignored; Toggle twice restores
A store with unsubscribe: Logs 1, 2, then 3; A fresh store works
The lesson lives in the companion repository at curriculum/level-03-interactive-web-applications/module-14-state-and-persistence/lesson-066-understanding-application-state/. Every example on this page is generated from those files.
These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.
15Summary and next steps
State is the data that decides what the app shows.
Keep it in one object, not in the page.
Store sources; compute derived values.
Change state through named update functions, and notify the UI after each change.
Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.
Concept explanationapplication state
Context: I am learning application state in JavaScript.
Task: Explain application state, derived values and update functions with a small cart example.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code predictionapplication state drill
Context: I have practised application state.
Task: Give me six small state-update programs and ask what the state is afterwards.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debuggingapplication state bug
Context: My cart count in the header shows a different number from the cart page.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generationapplication state practice
Context: I finished the application state exercises.
Task: Create three exercises about state objects, update functions and a small store.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code reviewapplication state review
Context: Here is my code that uses application state.
Task: Review my app for state stored in the DOM or duplicated in several variables.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.