JavaScript

LocalStorage & SessionStorage

Save data in the browser! Learn to use LocalStorage and SessionStorage to persist user data.

By TechCoder TeamLast updated: 2026-06-02
In a Nutshell

Save data in the browser! Learn to use LocalStorage and SessionStorage to persist user data. This hands-on tutorial focuses on practical implementation of localstorage & sessionstorage concepts.

LocalStorage & SessionStorage

Variables are great, but they disappear when you refresh the page. Web Storage allows you to save data in the user's browser so it stays there even after a reload.

1. LocalStorage vs. SessionStorage 🗄️

Both work exactly the same way, but they have different lifetimes.

| Feature | LocalStorage | SessionStorage | | :--- | :--- | :--- | | Lifetime | Forever (until deleted) | Session (until tab closes) | | Scope | Shared across tabs/windows | Specific to one tab | | Capacity | ~5-10 MB | ~5 MB |

Use Cases:

  • LocalStorage: Dark mode preference, Auth tokens, Shopping cart.
  • SessionStorage: Form data (multi-step forms), Temporary state.

2. Basic Operations (Strings Only) 💾

Web Storage can only store strings.

A. Saving Data (setItem)

JAVASCRIPT PLAYGROUND
⏳ Loading editor…

B. Retrieving Data (getItem)

JAVASCRIPT PLAYGROUND
⏳ Loading editor…

C. Removing Data (removeItem / clear)

JAVASCRIPT PLAYGROUND
⏳ Loading editor…

3. Storing Objects & Arrays 📦

Since storage only accepts strings, you cannot store objects directly. You must convert them to a JSON String first.

The Trick:

  1. Save: JSON.stringify(object)
  2. Load: JSON.parse(string)
JAVASCRIPT PLAYGROUND
⏳ Loading editor…

4. SessionStorage Example ⏱️

It works exactly the same! Just replace localStorage with sessionStorage.

JAVASCRIPT PLAYGROUND
⏳ Loading editor…

AI Mentor

Confused about "Web Storage API, LocalStorage, SessionStorage, and JSON serialization"? Ask our AI mentor for a simplified explanation.

Quiz

Quiz

Question 1 of 4

What data type does LocalStorage store?

Objects
Arrays
Strings only
Anything

Key Takeaways

LocalStorage = Permanent storage.
SessionStorage = Temporary (Tab) storage.
Strings Only: Use JSON.stringify and JSON.parse.
setItem, getItem, removeItem.

What's Next?

Now that we can save data, let's learn how to execute code after a delay with Timers!

Keep coding! 🚀