JavaScript lesson · 23 min

JavaScript localStorage

Save small browser preferences as strings and read them again later.

Code runs locally in your browser

What you will practice

  • Save values with localStorage.setItem.
  • Read values with localStorage.getItem.
  • Use JSON for non-string values.

What this means

`localStorage` stores small string values in the browser.

Values in localStorage stay after a page refresh and usually stay after the browser is closed.

Because storage values are strings, objects and arrays need `JSON.stringify` before saving and `JSON.parse` after reading.

If this is your first time seeing this

localStorage is browser memory for small strings that should survive page refreshes.

If you save an object or array, convert it with JSON first.

Mini glossary

localStorage
Browser storage for small string values that can persist across sessions.
setItem
Saves a string value under a key.
getItem
Reads a saved string value by key.

Example from everyday life

localStorage is like a small notebook kept in the browser. If a user chooses dark mode, the site can write that preference down and read it again on the next visit.

How it works step by step

  1. `setItem` saves a key-value pair.
  2. `getItem` reads the value by key.
  3. The example stores a plain theme string and a JSON list of completed lessons.
  4. `JSON.parse` turns the stored lesson list back into an array.

Where you will use this

  • Remembering light or dark theme.
  • Saving draft text locally before the user submits a form.
  • Keeping a simple course progress marker in the browser.

Before you run the code

Do not store passwords, tokens, private keys, or sensitive personal data in localStorage.

Use localStorage for small convenience state, not as a real database.

Common beginner mistakes

  • Trying to save an object without `JSON.stringify`.
  • Forgetting that `getItem` can return `null`.
  • Storing secrets or sensitive data in browser storage.

Run in browser

Try the example

Console output
Run the code to see console output here.
Exercise checks0 of 2 checks passed.
WaitingReads the saved theme
WaitingParses saved JSON data

Code runs locally in an isolated sandboxed browser frame with a timeout. It is not sent to Lumio analytics or executed on the server.

Try changing this next

  • Change the theme to `light`.
  • Add another completed lesson to the array.
  • Remove the saved theme with `localStorage.removeItem("lumio-theme")`.