Storage and state
Persist small amounts of state safely and keep the UI in sync with it.
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.
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());| Storage | Lifetime | Use it for |
|---|---|---|
| localStorage | Until cleared | Preferences and small progress |
| sessionStorage | One tab session | Draft state and wizard steps |
| In-memory variable | Until reload | Derived UI state |
Your turn
MediumSave and restore progress
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 inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.