HTML5 Local Storage

HTML5 Local Storage: Store Data That Sticks

Sometimes you need to save data in the browser — a username, a theme preference, a to-do list. That’s where localStorage and sessionStorage come in. They’re part of the Web Storage API and allow you to store key-value pairs in a user’s browser without cookies or server calls.

1. What Is localStorage?

localStorage stores data with no expiration time. It stays even when the browser is closed or the machine is restarted. Data is stored per domain and accessible via JavaScript.

Basic Example

<button onclick="saveFruit()">Save Apple</button>
<button onclick="getFruit()">Load Fruit</button>
<p id="output"></p>

<script>
function saveFruit() {
  localStorage.setItem("fruit", "Apple");
}

function getFruit() {
  const fruit = localStorage.getItem("fruit");
  document.getElementById("output").innerText = fruit ? "Saved: " + fruit : "No fruit found.";
}
</script>
[ Click "Save Apple" → then "Load Fruit" → Displays: "Saved: Apple" ]

2. What Is sessionStorage?

sessionStorage works like localStorage, but data only lasts for the duration of the browser tab. Close the tab, and it's gone. It’s perfect for temporary data like session state.

<button onclick="saveSessionFruit()">Save Cherry in Session</button>
<button onclick="getSessionFruit()">Load Session Fruit</button>
<p id="sessionOutput"></p>

<script>
function saveSessionFruit() {
  sessionStorage.setItem("fruit", "Cherry");
}

function getSessionFruit() {
  const fruit = sessionStorage.getItem("fruit");
  document.getElementById("sessionOutput").innerText = fruit ? "Session: " + fruit : "Session is empty.";
}
</script>

3. Setting, Getting, and Removing Data | Action | Code | |--------|------| | Save | localStorage.setItem("key", "value") | | Read | localStorage.getItem("key") | | Remove | localStorage.removeItem("key") | | Clear all | localStorage.clear() | Example: Clear Storage <button onclick="clearAll()">Clear Local Storage</button> <script> function clearAll() { localStorage.clear(); alert("Local storage cleared!"); } </script> 4. Use Cases for localStorage

| Action | Code | |--------|------| | Save | localStorage.setItem("key", "value") | | Read | localStorage.getItem("key") | | Remove | localStorage.removeItem("key") | | Clear all | localStorage.clear() |

Example: Clear Storage

<button onclick="clearAll()">Clear Local Storage</button>
<script>
function clearAll() {
  localStorage.clear();
  alert("Local storage cleared!");
}
</script>

4. Use Cases for localStorage

  • Remembering user preferences (e.g., dark mode)
  • Saving to-do lists, drafts, or shopping carts
  • Storing user-selected items like fruit: 🍌, 🍎, 🍒

5. Important Notes and Best Practices

  • Stored data is always a string. Use JSON.stringify() for objects.
  • Storage is domain-specific and limited (around 5MB per domain).
  • Do not store sensitive or personal data — it’s accessible to any script running on the page.

Storing an Array

const fruits = ["Apple", "Banana", "Cherry"];
localStorage.setItem("fruitList", JSON.stringify(fruits));

const loadedFruits = JSON.parse(localStorage.getItem("fruitList"));
console.log(loadedFruits); // Output: ["Apple", "Banana", "Cherry"]

Summary

HTML5’s Web Storage API gives you powerful tools for storing and retrieving data in the browser. You’ve learned how to:

  • Use localStorage to persist data
  • Use sessionStorage for temporary session-based storage
  • Work with key-value pairs using setItem, getItem, removeItem, and clear

Check your understanding 1

What is the main difference between localStorage and sessionStorage in HTML5?
Choose one answer. You can try again.

Answer and explanation

localStorage persists data even after the browser is closed; sessionStorage clears data when the tab is closed

localStorage saves data with no expiration date, so data remains even after closing the browser. sessionStorage data is cleared when the browser tab or window is closed.

Check your understanding 2

localStorage and sessionStorage can only store string key-value pairs in the browser.
Choose one answer. You can try again.

Answer and explanation

True

Both storage APIs store data as strings. To store objects or arrays, data must be serialized (e.g., using JSON.stringify) before storage.

Check your understanding 3

Choose the option that lists all and only the correct statements.

  1. setItem()
  2. getItem()
  3. removeItem()
  4. clear()
Which of the following methods are used to interact with localStorage or sessionStorage?
Choose one answer. You can try again.

Answer and explanation

Statements 1 and 2 and 3 and 4

All these methods are part of the Storage API: setItem() to store data, getItem() to retrieve, removeItem() to delete a specific key, and clear() to remove all stored data.

Check your understanding 4

How would you store the key 'studentName' with value 'Rajesh' in localStorage?
Choose one answer. You can try again.

Answer and explanation

localStorage.setItem('studentName', 'Rajesh');

The correct method to store data in localStorage is setItem(key, value).

Check your understanding 5

Data stored in localStorage is accessible by any page from the same domain.
Choose one answer. You can try again.

Answer and explanation

True

localStorage is scoped per origin (domain + protocol + port), so all pages from the same origin can access the stored data.

Check your understanding 6

Choose the option that lists all and only the correct statements.

  1. Saving user preferences (like theme or language)
  2. Storing login session tokens securely
  3. Caching frequently accessed data for offline use
  4. Temporary form data between page reloads
Which of the following are common use cases for localStorage in web applications?
Choose one answer. You can try again.

Answer and explanation

Statements 1 and 3 and 4

localStorage is good for persisting preferences, caching data for offline use, and storing temporary data like form entries. However, it’s not secure for sensitive data like login tokens.

What’s Next?

Next, we’ll look at how to sync localStorage with user interfaces, build mini data-driven apps like a to-do list, and explore IndexedDB for more complex structured storage.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: HTML5 contentEditable Attribute →