← Back to JavaScript
32

Browser persistence: `localStorage` and `sessionStorage`

Store useful client-side state with clear criteria: what to persist, how to serialize it and how to avoid inconsistent UI behavior.

📘 Theory

When storage helps and when it does not

Useful persistence is not the same as dumping everything into the browser.

  • Good candidates: theme choice, filters, draft values, last active tab.
  • Bad candidates: secrets, sensitive tokens and high-risk business data.
  • Good candidates: small, simple values and lightweight objects.
  • Bad candidates: giant blobs or data you cannot trust on the client.

Serialize and read objects properly

Storage only keeps strings, so you control the conversion.

1

Saving objects means converting them with `JSON.stringify()`. Reading them back means handling `null` safely and parsing them with `JSON.parse()`.

2

This is also where defaults matter. If the key is missing or corrupted, the UI still needs a stable fallback.

Hydrate at startup and persist after relevant changes

Storage only becomes useful when it reconnects to the interface correctly.

1

A common pattern is to hydrate the UI on load and persist after each meaningful state change.

2

If the interface changes but you forget to save, the next reload will surprise the user with stale state.

🧪 Learn by doing

Example Guided example: save preferences with JSON Persist a small preferences object and recover it safely.

🏁 Challenges

Challenge Challenge: store a value for the current session Save a small key in `sessionStorage` and read it back while the tab remains open.

🧰 Resources

Test

Check your knowledge with a test about JavaScript.

Test for JavaScript

What is this?

I'm Cristian Eslava and I sometimes build websites so both you and I can learn and experiment. culTest

I made this in February 2026 to make learning easier for my students. The idea is to learn web development by practicing and to keep expanding the project with new topics, tests and challenges.

It draws inspiration from MDN, W3Schools, CodePen, Manz and many other web development references. I wanted to combine useful theory, runnable examples, challenges and the testing system I had already built for culTest. culTest

If you liked it, if you didn't, or if you want to get in touch, write to me at cristianeslava@gmail.com