Session Storage
sessionStorage works exactly like localStorage, but it forgets everything when the tab is closed.
On this page · 5 min · Intermediate
On this page
- Learning objectives
- Explanation
- Code example
- Step by step
- Real-world use
- Common mistakes
- Best practices
- Remember this
- Practice exercise
- Mini quiz
- Related topics
- My notes
- Reading time
- 5 min
- Difficulty
- Intermediate
- Updated
- Oct 27, 2026
Related tutorials
Learning objectives#
- Use sessionStorage’s API
- Compare sessionStorage, localStorage and cookies
- Save a form draft for the current tab
- Pick the right storage for the job
Explanation#
sessionStorage has the same methods as localStorage: setItem, getItem, removeItem, clear.
Data lives only for the current tab. A reload keeps it; closing the tab deletes it. Another tab has its own separate sessionStorage.
It suits temporary state: a half-filled form, the current step of a checkout wizard, or a one-time message.
Code example: Never lose a half-written message#
<textarea id="msg" rows="4" placeholder="Write your message…"></textarea>
<script>
const box = document.querySelector('#msg');
box.value = sessionStorage.getItem('draft') ?? '';
box.addEventListener('input', () => sessionStorage.setItem('draft', box.value));
// after a successful send:
// sessionStorage.removeItem('draft');
</script>
Reloading the tab keeps the text you typed; closing the tab clears it. (Run this on your own page — sandboxed examples have no storage.)
This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.
Step-by-step explanation#
- On load, any saved draft is restored.
- Every keystroke saves the latest text.
- After sending, the draft is removed.
- A new tab starts with an empty sessionStorage.
Real-world use case#
Multi-step forms (shipping → payment → review) keep their progress if the user accidentally refreshes.
Common mistakes#
Use localStorage if data must persist between visits.
Each tab has its own sessionStorage.
Best practices#
- Use sessionStorage for temporary, per-tab state
- Clear drafts after successful submission
- Store non-sensitive data only
- Use JSON for structured data
Remember this#
local = remembers forever; session = remembers until the tab closes.
Same methods, different lifetime.
One tab, one sessionStorage.
Practice exercise#
Your task: Store the current wizard step (1–3) in sessionStorage and restore it on reload.
Show solution
let step = Number(sessionStorage.getItem('step') ?? 1);
function goTo(n) { step = n; sessionStorage.setItem('step', n); }
Mini quiz#
When is sessionStorage data deleted?
Want more? Practise all JavaScript MCQs · JavaScript interview questions
My notes#
Saved in this browser.