Web storage
These programs are page scripts: they run in a browser page and the lines under each one are what its console prints. A command-line Node program has no localStorage, so the same file started there stops with ReferenceError: localStorage is not defined.
localStorage set
localStorage keeps strings after the tab closes. setItem stores under a key, and getItem reads it back on the next visit. Both calls are synchronous, so keep stored values small:
localStorage.setItem("theme", "dark"); console.log(localStorage.getItem("theme"));
dark
Reload the page and the pair is still there. Keys are plain strings, so prefix them with the app name to avoid collisions. The program stores a theme and prints what comes back.
Read with fallback
getItem returns a string or null when the key was never stored. Provide a fallback with double question marks, so the rest of the code always sees a real string:
const theme: string = localStorage.getItem("theme") ?? "light"; console.log(theme);
light
The first visit reads light, later visits read the saved choice. One line, no if needed, and no null leaks further. The program prints light on its first visit, before anything is stored.
Store objects
Storage holds strings only, so stringify objects on the way in and parse them on the way out. Wrap both directions in helpers that fall back to defaults when the stored text is missing:
interface Prefs { theme: string; size: number; } function savePrefs(prefs: Prefs): void { localStorage.setItem("prefs", JSON.stringify(prefs)); } function loadPrefs(): Prefs { const raw = localStorage.getItem("prefs"); if (raw === null) { return { theme: "light", size: 14 }; } return JSON.parse(raw) as Prefs; } const first = loadPrefs(); savePrefs({ theme: "dark", size: 16 }); const second = loadPrefs(); console.log(first.theme, first.size); console.log(second.theme, second.size);
light 14
dark 16
The interface keeps the parsed value honest, and the early return covers fresh visitors. Every caller of loadPrefs receives complete prefs, never a hole. The program loads before anything is stored, saves a choice, and loads again.
sessionStorage
sessionStorage shares the same methods but a different lifetime: values vanish when the tab closes. Use it for per-tab state like a draft or a wizard step that must not leak into other tabs:
sessionStorage.setItem("draft", "hello"); const draft: string = sessionStorage.getItem("draft") ?? ""; console.log(draft);
hello
Same calls, tab-sized memory. Long-lived choices go to localStorage, temporary tab state goes here. The program stores a draft and prints it back from the same tab.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What can localStorage hold?
Answer
Strings only
Every value is stored as text, which is why objects are stringified on the way in and parsed on the way out.
-
What does
getItemreturn for a key that was never stored?Answer
nullThe missing key gives
null, and??turns it into a fallback with one operator. -
How long does a sessionStorage value live?
Answer
Until the tab is closed
The value belongs to one tab and disappears when that tab closes, which suits drafts and wizard steps.
-
Why parse a stored object instead of using it directly?
Answer
Because storage returns text, so the object must be rebuilt from JSON
The stored text is JSON, and
JSON.parserebuilds the object that the interface then describes. -
What does this program print?
const stored: string | null = null; const theme: string = stored ?? "light"; console.log(theme);Answer
light
A null on the left of
??gives the fallback string, which is the same shape a first visit to a page sees. -
What happens when
setItemis called twice with the same key?Answer
The second value replaces the first
A storage key holds one string, so a second write overwrites the value that was there.
-
What does this program print?
interface Prefs { theme: string; size: number; } function loadPrefs(raw: string | null): Prefs { if (raw === null) { return { theme: "light", size: 14 }; } return JSON.parse(raw) as Prefs; } console.log(loadPrefs(null).size);Answer
14
The missing text is the first-visit case, so the early return gives the default size of 14.
-
What does this program print?
const raw = JSON.stringify({ theme: "dark", size: 16 }); console.log(JSON.parse(raw).theme);Answer
dark
The text goes back through the parser into an object, and its theme field is printed.
-
What does the compiler say about this program?
const theme: string = localStorage.getItem("theme"); console.log(theme);Answer
error TS2322: Type 'string | null' is not assignable to type 'string'.
getItemmay givenull, and a variable declared as a plain string cannot hold that without a fallback. -
What does the compiler say about this program?
localStorage.setItem("draft", 5); console.log(localStorage.getItem("draft"));Answer
error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.
Storage takes text, so a number is refused until the program converts it with
String(value).
Article author: Arthur Isaev