JavaScript Foundations·Build and ship

Storage and state

Persist small amounts of state safely and keep the UI in sync with it.

Beginner 12 min read Lesson 12 of 480 Challenge included
What you will be able to do
  • Save and load JSON safely
  • Namespace your keys
  • Recover from corrupt stored data

localStorage keeps strings across visits. Serialise objects with JSON, namespace the key and treat stored data as untrusted input.

storage.jsJavaScript
const KEY = "edubyte:settings";

function loadSettings() {
  try {
    const raw = localStorage.getItem(KEY);
    return raw ? { theme: "light", ...JSON.parse(raw) } : { theme: "light" };
  } catch (error) {
    console.warn("Could not read settings", error);
    return { theme: "light" };
  }
}

function saveSettings(settings) {
  try {
    localStorage.setItem(KEY, JSON.stringify(settings));
  } catch (error) {
    console.warn("Could not save settings", error);
  }
}

const settings = loadSettings();
settings.theme = "dark";
saveSettings(settings);
console.log(loadSettings());
StorageLifetimeUse it for
localStorageUntil clearedPreferences and small progress
sessionStorageOne tab sessionDraft state and wizard steps
In-memory variableUntil reloadDerived UI state
Your turn

Save and restore progress

Medium

Write saveProgress and loadProgress for a versioned progress object. Return a safe default when nothing is stored.

JAVASCRIPT · starter
const KEY = "edubyte:progress";

function saveProgress(progress) {
  // your code here
}

function loadProgress() {
  // your code here
}
Check your understanding before moving on.
Knowledge checkQuestion 1

Why wrap JSON.parse in a try/catch when reading localStorage?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Errors and debugging
Lesson 12 of 480 · 0% of course