localStorage VS sessionStorage
The main difference
| Property | localStorage | sessionStorage |
|---|---|---|
| Storage time | Data is kept forever, until the user clears it or code removes it | Data is kept only while the tab/window is open |
| After a page reload | Kept | Kept |
| After closing the tab | Kept | Removed |
| Shared access between tabs of the same domain | Yes | No (each tab has its own storage) |
| Capacity | ~5-10 MB | ~5 MB |
| Data type | Strings only (uses JSON.stringify) | Strings only (also via JSON.stringify) |
| Access restriction | Same domain only | Same domain and same tab only |
| Common use | Themes, settings, tokens, cached data | Temporary 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 availableShort summary
| Storage | Lives | Shared data between tabs | Removed |
|---|---|---|---|
| localStorage | forever | yes | manually or by clearing the browser |
| sessionStorage | while the tab is open | no | when the tab is closed |
Remember it simply:
localStorageis persistent storage (for "long-lived" data).sessionStorageis temporary storage (for the "current session").
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.