Skip to main content
JavaScript Basics
CHAPTER 25 Beginner

JavaScript Local Storage and Session Storage

Updated: May 12, 2026
20 min read

# 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. 1. localStorage: Stores data with no expiration date. The data persists even if the browser is completely closed and reopened the next day.
  1. 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() and clear().
  • 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

javascript
1234567
// Example JavaScript
// 1. Save data
localStorage.setItem("username", "Alex99");

// 2. Retrieve data
let user = localStorage.getItem("username");
console.log(user); // Output: Alex99

---

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.

javascript
12345
// Example JavaScript
localStorage.setItem("theme", "light"); // Initial save
localStorage.setItem("theme", "dark");  // Overwrites "light"

console.log(localStorage.getItem("theme")); // Output: dark

Example 2: Removing Specific Items

If the user logs out, you want to delete their specific data, but not the whole app's settings.

javascript
12345
// Example JavaScript
localStorage.setItem("sessionToken", "abc123xyz");
localStorage.removeItem("sessionToken"); // Deleted!

console.log(localStorage.getItem("sessionToken")); // Output: null

Example 3: Clearing ALL Storage

If you want to completely wipe every piece of data your website has saved on this user's browser.

javascript
1234567
// Example JavaScript
localStorage.setItem("a", 1);
localStorage.setItem("b", 2);

localStorage.clear(); // Wipes everything

console.log(localStorage.getItem("a")); // null

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]".

javascript
123456
// Example JavaScript
const settings = { volume: 50, theme: "dark" };

// BAD
localStorage.setItem("config", settings);
console.log(localStorage.getItem("config")); // Output: [object Object] (Data is destroyed!)

Example 5: Storing Objects securely using JSON

To store complex data, you MUST use JSON.stringify() when saving, and JSON.parse() when retrieving.

javascript
1234567891011
// Example JavaScript
const userProfile = { id: 1, name: "Sarah" };

// 1. Stringify before saving
localStorage.setItem("profile", JSON.stringify(userProfile));

// 2. Parse after retrieving
const rawData = localStorage.getItem("profile");
const parsedData = JSON.parse(rawData);

console.log(parsedData.name); // Output: Sarah

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.

javascript
123456789
// Example JavaScript
let highscore = localStorage.getItem("score");

if (highscore === null) {
    // First time playing! Set a default.
    highscore = 0;
} else {
    console.log("Welcome back. Your highscore is " + highscore);
}

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).

javascript
123456
// Example JavaScript
// User fills out Step 1 of the checkout
sessionStorage.setItem("shippingAddress", "123 Main St");

// They refresh the page, data is still there!
// They close the tab, data is instantly deleted.

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.

javascript
123456789
// Example JavaScript
// 1. Get array (or create empty one if null)
let cart = JSON.parse(localStorage.getItem("cart")) || [];

// 2. Modify array
cart.push("Shoes");

// 3. Save it back
localStorage.setItem("cart", JSON.stringify(cart));

Example 10: Viewing Storage in DevTools

You can actually see your Local Storage data visually!

  1. 1. Right-click your webpage and select "Inspect" to open Chrome DevTools.
  1. 2. Click the "Application" tab (you might have to click the >> arrows).
  1. 3. On the left sidebar, click "Local Storage", then click your website's URL.
  1. 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. 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!
  1. 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 you JSON.parse() it back into an array.
  1. 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:

html
12345678910111213141516171819202122232425262728
<!-- Example HTML -->
<!DOCTYPE html>
<html>
<head>
    <style>
        /* Example CSS */
        body { font-family: sans-serif; padding: 50px; transition: 0.3s; }
        
        /* Light Theme (Default) */
        .theme-light { background: #ffffff; color: #333333; }
        .theme-light button { background: #333; color: white; }
        
        /* Dark Theme */
        .theme-dark { background: #222222; color: #ffffff; }
        .theme-dark button { background: #fff; color: #333; }
        
        button { padding: 15px 25px; border: none; cursor: pointer; border-radius: 5px; font-weight: bold;}
    </style>
</head>
<body class="theme-light" id="appBody">

    <h1>Settings</h1>
    <p>Refresh the page. I will remember your choice.</p>
    <button onclick="toggleTheme()">Toggle Dark Mode</button>

    <script src="storage.js"></script>
</body>
</html>

storage.js:

javascript
12345678910111213141516171819202122232425262728
// Example JavaScript
const body = document.getElementById("appBody");

// 1. Check storage immediately when the script runs
function initializeTheme() {
    // Get the saved theme, default to 'light' if null
    const savedTheme = localStorage.getItem("userTheme") || "light";
    
    // Apply the saved theme class
    body.className = `theme-${savedTheme}`;
}

// 2. The Toggle function
function toggleTheme() {
    // Check what the current theme is
    if (body.classList.contains("theme-light")) {
        // Switch to Dark
        body.className = "theme-dark";
        localStorage.setItem("userTheme", "dark"); // Save it!
    } else {
        // Switch to Light
        body.className = "theme-light";
        localStorage.setItem("userTheme", "light"); // Save it!
    }
}

// Run the initialization on load
initializeTheme();

9. Exercises

  1. 1. Write code to save a key "score" with a value of 100 to localStorage.
  1. 2. Write code to retrieve the "score", add 50 to it, and save it back. (Hint: Remember it comes out as a String, so you must use Number() before adding!).
  1. 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

  • localStorage persists data forever.
  • sessionStorage persists data only until the tab closes.
  • Use setItem(key, value) and getItem(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 using try...catch and keep our apps running smoothly.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·