JavaScript · Browser Storage

Local Storage

localStorage lets a website remember small pieces of data on the visitor’s device — even after they close the browser.

Intermediate 5 min Lesson 36 of 49
Before you start:JSON
0/49 in JavaScript
On this page · 5 min · Intermediate

Learning objectives#

  • Save and read values with setItem and getItem
  • Store objects as JSON
  • Remove items
  • Know localStorage’s limits and safe uses

Explanation#

localStorage stores string key–value pairs per website (origin), about 5 MB, with no expiry.

setItem(key, value) saves, getItem(key) reads (null if missing), removeItem(key) deletes, clear() deletes everything.

Only strings are stored, so use JSON.stringify and JSON.parse for objects and arrays.

Anything in localStorage can be read by any script on the page, so never store passwords or tokens there.

Code example: A theme that remembers itself#

HTMLA theme that remembers itself Illustrative
<button id="toggle">Toggle theme</button>
<script>
  const saved = localStorage.getItem('theme') ?? 'light';
  document.body.dataset.theme = saved;


  document.querySelector('#toggle').addEventListener('click', () => {
    const next = document.body.dataset.theme === 'dark' ? 'light' : 'dark';
    document.body.dataset.theme = next;
    localStorage.setItem('theme', next);
  });


  // Objects must be stored as JSON
  const prefs = { fontSize: 18, lang: 'en' };
  localStorage.setItem('prefs', JSON.stringify(prefs));
  const loaded = JSON.parse(localStorage.getItem('prefs'));
  console.log(loaded.fontSize);   // 18
</script>
Expected output
The chosen theme is still applied after a page reload, and 18 is logged. (This example uses real storage, so run it in the playground or your own page — runnable lesson examples are sandboxed without 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. getItem returns the saved theme or null; ?? falls back to "light".
  2. Clicking the button flips the theme and saves it.
  3. On the next visit, the saved value is read and applied immediately.
  4. Objects are saved as JSON text and parsed back.

Real-world use case#

Remembering dark mode, a shopping cart for guests, the last tab opened, or a draft message. (Techie Babaji saves your guest progress this way.)

Common mistakes#

Storing objects directly

localStorage.setItem('u', { a: 1 }) stores "[object Object]". Use JSON.stringify.

Storing secrets

Tokens in localStorage can be stolen by any XSS bug. Use httpOnly cookies for authentication.

Best practices#

  • Wrap storage access in try…catch (it can be blocked in private mode)
  • Store small, non-sensitive data only
  • Version your keys (prefs-v1) so you can change the format later
  • Validate data read back from storage

Remember this#

localStorage = a small notebook that stays on the device.

Strings only — JSON.stringify in, JSON.parse out.

No secrets in localStorage.

Practice exercise#

Your task: Count how many times the visitor has opened the page and show “Visit #3” on the third visit.

Show solution
JavaScript Illustrative
const visits = Number(localStorage.getItem('visits') ?? 0) + 1;
localStorage.setItem('visits', visits);
document.body.prepend(`Visit #${visits}`);

Mini quiz#

Local Storage quizMultiple choice Question 1 of 1

What does getItem return for a key that does not exist?

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.