JavaScript AcademyProfessional Engineering
Level 3 · Interactive Web ApplicationsModule 14: State and PersistenceLesson 66 of 150About 40 minutes

Lesson 66: Understanding application state

01Opening question

Where does your app keep the truth: in the page, or in your variables?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

State is the data that decides what the app shows. Keeping it in one object, changed only by named functions, makes the app predictable.

const state = { items: ["Milk"], filter: "all" };
function addItem(name) {
  state.items = [...state.items, name];
}
addItem("Bread");
console.log(state.items.length, state.items.join(", "));

03Objective and prerequisites

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.

You need: Lesson 65: Accessible form feedback, Lesson 40: Modeling real-world information

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.

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.

Open the full glossary

06Visual learning object

Application state visualizer. Dispatch actions on a small cart and watch the state object change step by step, with derived values recomputed beside it.

Loading the interactive object…

Open the full Application state visualizer page with its guided experiment.

07Examples

ex-066-01The page is not the source of truth Browser page (sandboxed preview)

Reading numbers back from text is fragile; a variable is reliable.

const count = document.querySelector("#count");
count.textContent = Number(count.textContent) + 1;
count.textContent = "three";
console.log(Number(count.textContent) + 1);
const state = { count: 2 };
state.count++;
count.textContent = state.count;
console.log(state.count + 1);
Sample input
None
Expected output
NaN 4
Common mistake
Reading state back from text the user (or another script) can change.
Try this
Store the items themselves and derive the count.
Source
examples/ex-066-01-dom-as-state.js

ex-066-02Store sources, derive the rest Browser page (sandboxed preview)

The total is computed from items, so it can never be out of date.

const state = { items: [{ name: "Tea", price: 4 }, { name: "Mug", price: 12 }] };
const total = (s) => s.items.reduce((sum, i) => sum + i.price, 0);
console.log(total(state));
state.items.push({ name: "Spoon", price: 3 });
console.log(total(state));
document.querySelector("#total").textContent = "$" + total(state);
console.log(document.querySelector("#total").textContent);
Sample input
None
Expected output
16 19 $19
Common mistake
Keeping a separate total variable and forgetting to update it when items change.
Try this
Add a derived itemCount.
Source
examples/ex-066-02-derived.js

ex-066-03Named update functions Browser page (sandboxed preview)

Every change goes through a function, so rules live in one place.

const state = { cart: [] };
function addToCart(id) {
  const line = state.cart.find((l) => l.id === id);
  if (line) line.qty++;
  else state.cart.push({ id, qty: 1 });
}
function removeFromCart(id) {
  state.cart = state.cart.filter((l) => l.id !== id);
}
addToCart("lamp"); addToCart("lamp"); addToCart("desk"); removeFromCart("desk");
console.log(JSON.stringify(state.cart));
Sample input
None
Expected output
[{"id":"lamp","qty":2}]
Common mistake
Pushing to state.cart from many places, each with slightly different rules.
Try this
Add setQty(id, qty) that removes the line when qty is 0.
Source
examples/ex-066-03-update-functions.js

ex-066-04A tiny store with subscribers Browser page (sandboxed preview)

Subscribers run after every update, which is how the UI stays in sync.

function createStore(initial) {
  let state = initial;
  const listeners = [];
  return {
    get: () => state,
    update(fn) {
      state = fn(state);
      listeners.forEach((l) => l(state));
    },
    subscribe: (l) => listeners.push(l)
  };
}
const store = createStore({ likes: 0 });
store.subscribe((s) => { document.querySelector("#out").textContent = s.likes; });
store.subscribe((s) => console.log("likes is now", s.likes));
store.update((s) => ({ ...s, likes: s.likes + 1 }));
store.update((s) => ({ ...s, likes: s.likes + 1 }));
console.log(document.querySelector("#out").textContent);
Sample input
None
Expected output
likes is now 1 likes is now 2 2
Common mistake
Changing state directly with store.get().likes++, which skips the subscribers.
Try this
Return an unsubscribe function from subscribe.
Source
examples/ex-066-04-store.js

08Guided exercises

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.

const state = { items: ["a"] };
const copy = state.items;
state.items = [...state.items, "b"];
console.log(copy.length, state.items.length);

What is printed?

10Debugging investigation

The unread count goes negative

Marking the same message as read twice makes the unread count go below the number of unread messages, eventually negative.

const state = {
  messages: [{ id: 1, read: false }, { id: 2, read: false }],
  unread: 2
};
function markRead(id) {
  state.messages.find((m) => m.id === id).read = true;
  state.unread--;
}
const unreadCount = () => state.unread;
markRead(1);
markRead(1);
document.querySelector("#unread").textContent = unreadCount();
console.log("Unread: " + unreadCount());

More cases in the Debugging Detective Laboratory

11Practical scenario

Shopping carts across a site

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.

const cart = [{ id: "lamp", qty: 2 }, { id: "mug", qty: 1 }];
const count = cart.reduce((n, l) => n + l.qty, 0);
console.log("header:", count, "drawer:", count, "checkout:", count);

12Knowledge check

1. What is application state?

  • The CSS of the page
  • The data the app keeps that decides what it shows
  • The HTML file
  • The browser version

2. Why compute a total instead of storing it?

  • It is faster always
  • A derived value cannot get out of sync with its source
  • Totals cannot be stored
  • JSON cannot hold numbers

3. Why does the header show the old count after adding an item?

state.items.push(item);
header.textContent = state.count;
  • count was stored separately and not updated
  • push is broken
  • length is wrong
  • The header is read-only

4. What is printed?

const s = { n: 0 };
const inc = () => { s.n++; };
inc(); inc();
console.log(s.n);
  • 1
  • 2
  • undefined
  • NaN

5. What does a store's subscribe let you do?

  • Change state
  • Run code after every state change
  • Save to disk
  • Create a component

6. Which is easier to debug?

  • Any code can change state anywhere
  • State changes only through named update functions
  • State kept only in the DOM
  • Global variables per feature

13Solutions and tests

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

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

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.

16AI learning prompts

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 explanation application 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 prediction application 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.
Debugging application 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 generation application 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 review application 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.