TaskSet 'cart' to 'session-only' in sessionStorage and 'persistent' in localStorage. Log sessionStorage.getItem('cart') and localStorage.getItem('cart'). Then sessionStorage.clear() and log sessionStorage.getItem('cart') again (expect 'null').
sessionStorage vs localStorage
75 XP5 min
Theory
Same API, different lifetime
sessionStorage has the exact same shape as localStorage β setItem, getItem, removeItem, clear, length. The difference is the lifetime:
| Storage | Survives reload? | Survives tab close? | Shared across tabs? |
| localStorage | yes | yes | yes (same origin) |
| sessionStorage | yes | NO | NO (per tab) |
When to pick which
- localStorage β anything the user expects to come back: theme, locale, lesson progress, draft autosave.
- sessionStorage β temporary tab state: "did the user dismiss this banner this session?", "step 2 of a 3-step form", a one-shot return URL.
Same key, different store
You can use the same key name in both β they're separate stores:
sessionStorage.setItem("token", "abc"); // gone when tab closes
localStorage.setItem("token", "abc"); // sticks aroundIn-memory third option
For things that should NEVER persist (passwords, in-flight payment data), use a plain JS variable. Don't reach for storage when memory is enough.
π
Sign up to start coding
Theory is open to everyone. The interactive editor, live preview, and check are unlocked with a 7-day free trial β card required, cancel anytime.
Sign up β free trial βFirst 10 lessons in each track are free. No card needed for those.