Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 11.3 — localStorage and sessionStorage
JavaScript · Example 2 of 3 ES2018+

A theme switch that remembers (safe loader with defaults)

The broken saved value didn't crash the page: the loader fell back to defaults. Tick the box: the page turns dark and the stored JSON updates. On a real site it would still be dark after a reload.

localStorage keeps small string key–value pairs for an origin across visits, sessionStorage keeps them for one tab; both store only strings (so use JSON), hold about 5 MB, block while they work, and must never hold secrets, because any script on the page can read them.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write saveList(key, array) and loadList(key) that store an array as JSON. loadList must return [] when nothing is stored or the stored text is broken.

02

Make a visit counter: read visits from localStorage, add 1, save it, and print Visit number N. (In the preview it always prints 1, because storage resets on each Run.)

Explain it without notes

01

Compare localStorage, sessionStorage and cookies: lifetime, scope, size and who can read them.

02

Why do you need JSON.stringify and JSON.parse with Web Storage, and what goes wrong without them?

03

Why shouldn't you store an authentication token in localStorage?

04

How does the storage event work?

A theme switch that remembers (safe loader with defaults) ES2018+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

bad saved settings, using defaults: SyntaxError
{ dark: false, size: 16 }
{"dark":false,"size":16}