Μετάβαση στο κύριο περιεχόμενο
← ⚡ JavaScript & the browser·Ενότητα C9 · Μάθημα 3
ΕργασίαSet '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
Θεωρία

Same API, different lifetime

sessionStorage has the exact same shape as localStorage — setItem, getItem, removeItem, clear, length. The difference is the lifetime:

StorageSurvives reload?Survives tab close?Shared across tabs?
localStorageyesyesyes (same origin)
sessionStorageyesNONO (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 around

In-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.

🔒

Εγγράψου για να αρχίσεις να προγραμματίζεις

Η θεωρία είναι ανοιχτή για όλους. Ο επεξεργαστής, η ζωντανή προεπισκόπηση και ο έλεγχος ξεκλειδώνουν με 7-ήμερη δωρεάν δοκιμή — απαιτείται κάρτα.

Εγγραφή — δωρεάν δοκιμή →

Τα πρώτα 10 μαθήματα κάθε διαδρομής είναι δωρεάν. Δεν χρειάζεται κάρτα.

← ΠροηγούμενοΕπόμενο μάθημα →

Μια συμβουλή Python ή web την ημέρα — με email

Σύντομο, γραμμένο στο χέρι, χωρίς spam. Διαγραφή με ένα κλικ.