Persist small preferences with Web Storage
Quick answer
Web Storage stores string key–value pairs. localStorage is associated with an origin and may persist beyond the current session; sessionStorage is scoped to an origin and a top-level browsing context’s session. Access or writes may fail because of policy or quota. Use JSON for small structured preferences and handle errors. Do not store secrets or assume storage is durable, private from scripts, or always enabled.
Browser examples
Run each snippet in a fresh browser document. These are static code blocks; ByteMind browser execution is not verified. Storage examples require a test origin.
const s=sessionStorage;try{s.setItem("bytemind-demo-theme","dark");console.log(s.getItem("bytemind-demo-theme"));}finally{s.removeItem("bytemind-demo-theme");}Expected console output:
darkThe value is retrieved as text; cleanup removes the temporary key.
const s=localStorage,k="bytemind-demo-count";try{s.removeItem(k);console.log(s.getItem(k)===null);s.setItem(k,0);console.log(typeof s.getItem(k),s.getItem(k));}finally{s.removeItem(k);}Expected console output:
truestring 0A missing key returns null; numeric input is converted to a string.
Common mistake
Do not store authentication secrets or sensitive personal data here. Check for null when a key is absent; the stored string "null" is different from absence.
Practice
Implement a local theme preference with a default when storage is unavailable or the stored value is unexpected.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Persist small preferences with Web Storage — Knowledge Check
Apply the concept and predict the browser example behavior.
What does getItem return for an absent key?
Which storage is scoped to a top-level browsing context session and origin?
Why wrap storage access in error handling?
What is the exact console output in Persist small preferences with Web Storage example 1?
const s=sessionStorage;try{s.setItem("bytemind-demo-theme","dark");console.log(s.getItem("bytemind-demo-theme"));}finally{s.removeItem("bytemind-demo-theme");}What is the exact console output in Persist small preferences with Web Storage example 2?
const s=localStorage,k="bytemind-demo-count";try{s.removeItem(k);console.log(s.getItem(k)===null);s.setItem(k,0);console.log(typeof s.getItem(k),s.getItem(k));}finally{s.removeItem(k);}