LocalStorage & SessionStorage
Save data in the browser! Learn to use LocalStorage and SessionStorage to persist user data.
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)
B. Retrieving Data (getItem)
C. Removing Data (removeItem / clear)
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:
- Save:
JSON.stringify(object) - Load:
JSON.parse(string)
4. SessionStorage Example ⏱️
It works exactly the same! Just replace localStorage with sessionStorage.
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 4What data type does LocalStorage store?
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! 🚀