JavaScript · Browser Storage

Session Storage

sessionStorage works exactly like localStorage, but it forgets everything when the tab is closed.

Intermediate 5 min Lesson 37 of 49
Before you start:Local Storage
0/49 in JavaScript
On this page · 5 min · Intermediate

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#

HTMLNever lose a half-written message Illustrative
<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>
Expected output
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#

  1. On load, any saved draft is restored.
  2. Every keystroke saves the latest text.
  3. After sending, the draft is removed.
  4. 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#

Expecting it to survive closing the tab

Use localStorage if data must persist between visits.

Expecting it to be shared between tabs

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
JavaScript Illustrative
let step = Number(sessionStorage.getItem('step') ?? 1);
function goTo(n) { step = n; sessionStorage.setItem('step', n); }

Mini quiz#

Session Storage quizMultiple choice Question 1 of 1

When is sessionStorage data deleted?

Score so far: 0/0

Want more? Practise all JavaScript MCQs · JavaScript interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.