Skip to main content

localStorage VS sessionStorage

The main difference

PropertylocalStoragesessionStorage
Storage timeData is kept forever, until the user clears it or code removes itData is kept only while the tab/window is open
After a page reloadKeptKept
After closing the tabKeptRemoved
Shared access between tabs of the same domainYesNo (each tab has its own storage)
Capacity~5-10 MB~5 MB
Data typeStrings only (uses JSON.stringify)Strings only (also via JSON.stringify)
Access restrictionSame domain onlySame domain and same tab only
Common useThemes, settings, tokens, cached dataTemporary state, filters, drafts, session tokens

Code example (the same API)

javascript
// localStorage localStorage.setItem('theme', 'dark'); console.log(localStorage.getItem('theme')); // "dark" // sessionStorage sessionStorage.setItem('step', '2'); console.log(sessionStorage.getItem('step')); // "2"

After closing the tab:

  • localStorage -> the value remains,
  • sessionStorage -> it is cleared automatically.

When to use which

localStorage - for "long-lived" data

Use it when data needs to survive after the browser is closed:

  • the chosen theme (dark/light),
  • a remembered login,
  • a shopping cart,
  • user settings.

sessionStorage - for "temporary" data

Use it when you need to store state within a single session:

  • temporary forms and filters,
  • the step state in a registration wizard,
  • a session auth token.

Example of a practical difference

javascript
// in the first tab localStorage.setItem('color', 'red'); sessionStorage.setItem('page', 'home'); // in a second tab of the same site: console.log(localStorage.getItem('color')); // "red" available console.log(sessionStorage.getItem('page')); // null not available

Short summary

StorageLivesShared data between tabsRemoved
localStorageforeveryesmanually or by clearing the browser
sessionStoragewhile the tab is opennowhen the tab is closed

Remember it simply:

  • localStorage is persistent storage (for "long-lived" data).
  • sessionStorage is temporary storage (for the "current session").

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.