JavaScript Local Storage and Session Storage
# JavaScript Local Storage and Session Storage
If you close this tab right now and reopen it, everything you typed into a form or clicked on is gone. By default, the browser's memory is wiped clean the moment a tab is closed.
But what if you want to remember a user's "Dark Mode" preference or save the items in their shopping cart without building a massive backend database? This is where the Web Storage API comes in.
1. Introduction
The Web Storage API provides two mechanisms for storing data securely in the user's browser:
-
1.
localStorage: Stores data with no expiration date. The data persists even if the browser is completely closed and reopened the next day.
-
2.
sessionStorage: Stores data for one session. The data is destroyed the moment the specific browser tab is closed.
2. Learning Objectives
By the end of this chapter, you will be able to:
-
Save primitive data to local storage using
setItem().
-
Retrieve data using
getItem().
-
Delete data using
removeItem()andclear().
- Understand why you must use JSON to store Arrays and Objects.
- Build a persistent Dark Mode UI toggle mini-project.
3. Basic Syntax
Both localStorage and sessionStorage use the exact same methods. Data is always stored as Key-Value pairs (just like objects), and both the key and the value MUST be strings.
-
localStorage.setItem(key, value)
-
localStorage.getItem(key)
-
localStorage.removeItem(key)
-
localStorage.clear()
4. Saving and Retrieving Strings
---
5. Real-world Examples & Code Snippets
Example 1: Updating Existing Data
If you use setItem with a key that already exists, it will overwrite the old value.
Example 2: Removing Specific Items
If the user logs out, you want to delete their specific data, but not the whole app's settings.
Example 3: Clearing ALL Storage
If you want to completely wipe every piece of data your website has saved on this user's browser.
Example 4: The Array/Object Trap
CRITICAL RULE: Local Storage can ONLY store text strings. If you try to save an Array or Object directly, JavaScript will convert it to the useless string "[object Object]".
Example 5: Storing Objects securely using JSON
To store complex data, you MUST use JSON.stringify() when saving, and JSON.parse() when retrieving.
Example 6: Checking if Data Exists
If you getItem for a key that doesn't exist, it returns null. You should always check if data exists before trying to use it.
Example 7: Using Session Storage
If you only want data to survive page reloads, but be destroyed when the tab is closed, use sessionStorage. It is perfect for multi-step forms (like checkout processes).
Example 8: Storage Limits
Local Storage is not infinite. Most browsers limit it to about 5MB per domain. Do not try to store massive high-resolution images or gigabytes of data here.
Example 9: Synchronizing State
Often, you want to store a Javascript array, update it, and re-save it. You must pull it out, parse it, push to it, stringify it, and put it back.
Example 10: Viewing Storage in DevTools
You can actually see your Local Storage data visually!
- 1. Right-click your webpage and select "Inspect" to open Chrome DevTools.
-
2.
Click the "Application" tab (you might have to click the
>>arrows).
- 3. On the left sidebar, click "Local Storage", then click your website's URL.
- 4. You will see a table of your Keys and Values. You can even edit or delete them right there!
---
6. Common Mistakes for Beginners
-
1.
Forgetting
JSON.stringify(): Storing an array[1, 2, 3]directly will save it as the string"1,2,3". Storing an object{a: 1}will save it as"[object Object]". Always stringify!
-
2.
Forgetting
JSON.parse(): If you retrieve a stringified array, it's just a text string. You cannot run.map()or.push()on it until youJSON.parse()it back into an array.
- 3. Using Local Storage for Passwords: NEVER store passwords, credit card numbers, or highly sensitive data in Local Storage. Any malicious JavaScript running on the page (via a rogue third-party ad or plugin) can read Local Storage easily (XSS attacks).
7. Best Practices
- Use Local Storage for user preferences (theme, language), caching non-sensitive data, and saving "drafts" of forms.
-
Use
let data = JSON.parse(localStorage.getItem("key")) || []to safely fall back to an empty array if the storage is empty.
8. Mini Project: Persistent Theme Toggler
Let's build a UI with a "Dark Mode" button. If the user clicks it, we save that preference. If they refresh the page, the screen should immediately be dark.
HTML:
storage.js:
9. Exercises
-
1.
Write code to save a key
"score"with a value of100tolocalStorage.
-
2.
Write code to retrieve the
"score", add50to it, and save it back. (Hint: Remember it comes out as a String, so you must useNumber()before adding!).
-
3.
Write code to completely clear all
sessionStorage.
10. MCQs (Multiple Choice Questions)
Q1: What happens to sessionStorage when the user closes the browser tab?
A) It is permanently saved to the hard drive.
B) It is uploaded to a cloud database.
C) It is completely destroyed.
D) It is moved to localStorage.
*Answer: C*
Q2: Which method retrieves data from Local Storage?
A) localStorage.pull()
B) localStorage.getItem()
C) localStorage.read()
D) localStorage.fetch()
*Answer: B*
Q3: What will localStorage.setItem("user", {name: "John"}) save in the browser?
A) {"name": "John"}
B) [object Object]
C) John
D) undefined
*Answer: B (Because you forgot JSON.stringify!)*
11. Interview Questions
Q: What is the difference between Local Storage and Cookies? *A: Cookies are very small (4KB), are sent to the server automatically with every HTTP request, and have built-in expiration dates. Local Storage is much larger (5MB), is strictly client-side (never sent to the server automatically), and has no expiration date.*
12. FAQs
Q: Is Local Storage secure? *A: No. Any JavaScript running on your website can access Local Storage. Do not store JWTs (Authentication Tokens), Passwords, or personal data there.*
13. Summary
-
localStoragepersists data forever.
-
sessionStoragepersists data only until the tab closes.
-
Use
setItem(key, value)andgetItem(key).
- Keys and Values MUST be strings.
-
Use
JSON.stringify()to store Objects/Arrays.
-
Use
JSON.parse()to retrieve Objects/Arrays.
14. Next Chapter Recommendation
We just learned about things that can go wrong: parsing invalid JSON, trying to fetch data from dead servers, or failing to stringify objects. When things go wrong, applications crash. In the next chapter, JavaScript Error Handling, we will learn how to intercept crashes usingtry...catch and keep our apps running smoothly.