Command Palette

Search for a command to run...

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

sessionStorage: keep a form draft for this tab

The code fakes one keystroke and one click so the console has something to show. Type in the box yourself afterwards and watch the status line.

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?

sessionStorage: keep a form draft for this tab ES2020+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

draft: Hello Asha
after send: null