Command Palette

Search for a command to run...

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

Everything becomes a string

false was stored as the string "false", which is truthy. The object became "[object Object]". JSON fixes both. Real browsers may list keys in a different order; never rely on it.

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?

Everything becomes a string

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

string 51
truthy!
[object Object]
null
6
Asha
keys: 3
  count
  isAdmin
  user