Lesson 25 of 30

Local Storage

Storing Data in the Browser

Local Storage allows you to store data in the user's browser that persists even after closing the browser or restarting the computer.

Data is stored as key-value pairs in string format, so you'll need to use JSON.stringify/parse for objects and arrays.

Local Storage is perfect for saving user preferences, form data, shopping carts, and other client-side data up to about 5-10MB.

Example
// Save data to localStorage
localStorage.setItem('username', 'Alice');
localStorage.setItem('theme', 'dark');

// Get data from localStorage
const username = localStorage.getItem('username');
console.log(username); // "Alice"

// Remove specific item
localStorage.removeItem('theme');

// Clear all localStorage data
localStorage.clear();

// Storing objects (must convert to JSON)
const user = {
  name: 'Bob',
  age: 30,
  preferences: { theme: 'dark', language: 'en' }
};

// Save object as JSON string
localStorage.setItem('user', JSON.stringify(user));

// Retrieve and parse object
const savedUser = JSON.parse(localStorage.getItem('user'));
console.log(savedUser.name); // "Bob"

// Check if key exists
if (localStorage.getItem('username') !== null) {
  console.log('Username exists!');
}

// Get number of items
console.log(localStorage.length);

// Iterate through all items
for (let i = 0; i < localStorage.length; i++) {
  const key = localStorage.key(i);
  const value = localStorage.getItem(key);
  console.log(key, value);
}
  • setItem(key, value) - Store data with a key
  • getItem(key) - Retrieve data by key (returns null if not found)
  • removeItem(key) - Delete specific item
  • clear() - Remove all localStorage data
  • key(index) - Get key name at specific index
  • length - Number of items stored
  • Storage Limit: Typically 5-10MB per domain
  • Persistence: Data persists indefinitely until manually cleared
Try Local Storage
HTML
<div class="storage-demo">
  <h3>Local Storage Examples</h3>

  <div class="example">
    <h4>1. Save & Retrieve Simple Data</h4>
    <input type="text" id="key" placeholder="Key (e.g., username)">
    <input type="text" id="value" placeholder="Value (e.g., John)">
    <button id="saveBtn">Save</button>
    <button id="loadBtn">Load</button>
    <div id="simpleOutput"></div>
  </div>

  <div class="example">
    <h4>2. Save User Preferences</h4>
    <label>
      <input type="checkbox" id="darkMode"> Dark Mode
    </label>
    <label>
      <input type="checkbox" id="notifications"> Notifications
    </label>
    <select id="language">
      <option value="en">English</option>
      <option value="es">Español</option>
      <option value="fr">Français</option>
    </select>
    <button id="savePrefsBtn">Save Preferences</button>
    <button id="loadPrefsBtn">Load Preferences</button>
    <div id="prefsOutput"></div>
  </div>

  <div class="example">
    <h4>3. View All Stored Data</h4>
    <button id="viewAllBtn">View All Storage</button>
    <button id="clearAllBtn">Clear All Storage</button>
    <div id="allOutput"></div>
  </div>
</div>
CSS
.storage-demo {
  padding: 20px;
  max-width: 700px;
}

.example {
  margin: 20px 0;
  padding: 15px;
  background: #f5f5f5;
  border-radius: 8px;
}

h4 {
  margin-top: 0;
  color: #333;
}

input[type="text"], select {
  width: calc(50% - 10px);
  padding: 8px;
  margin: 5px;
  border: 2px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

label {
  display: block;
  margin: 10px 0;
  cursor: pointer;
}

input[type="checkbox"] {
  margin-right: 8px;
  cursor: pointer;
}

button {
  padding: 10px 15px;
  margin: 5px;
  background: #2196F3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

button:hover {
  background: #1976D2;
}

#clearAllBtn {
  background: #f44336;
}

#clearAllBtn:hover {
  background: #d32f2f;
}

#simpleOutput, #prefsOutput, #allOutput {
  margin-top: 10px;
  padding: 12px;
  background: white;
  border: 2px solid #ddd;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  min-height: 40px;
}

.success {
  border-color: #4CAF50 !important;
  background-color: #e8f5e9 !important;
  color: #2e7d32;
}

.info {
  border-color: #2196F3 !important;
  background-color: #e3f2fd !important;
}
JavaScript
// Example 1: Save & Retrieve Simple Data
document.getElementById('saveBtn').addEventListener('click', function() {
  const key = document.getElementById('key').value;
  const value = document.getElementById('value').value;
  const output = document.getElementById('simpleOutput');

  if (!key || !value) {
    output.textContent = 'Please enter both key and value!';
    return;
  }

  localStorage.setItem(key, value);
  output.className = 'success';
  output.textContent = `✓ Saved: "${key}" = "${value}"`;
});

document.getElementById('loadBtn').addEventListener('click', function() {
  const key = document.getElementById('key').value;
  const output = document.getElementById('simpleOutput');

  if (!key) {
    output.textContent = 'Please enter a key to load!';
    return;
  }

  const value = localStorage.getItem(key);

  if (value !== null) {
    output.className = 'success';
    output.textContent = `✓ Loaded: "${key}" = "${value}"`;
    document.getElementById('value').value = value;
  } else {
    output.textContent = `Key "${key}" not found in storage.`;
  }
});

// Example 2: Save User Preferences
document.getElementById('savePrefsBtn').addEventListener('click', function() {
  const preferences = {
    darkMode: document.getElementById('darkMode').checked,
    notifications: document.getElementById('notifications').checked,
    language: document.getElementById('language').value,
    savedAt: new Date().toLocaleString()
  };

  localStorage.setItem('userPreferences', JSON.stringify(preferences));

  const output = document.getElementById('prefsOutput');
  output.className = 'success';
  output.textContent = '✓ Preferences saved successfully!\n' +
    JSON.stringify(preferences, null, 2);
});

document.getElementById('loadPrefsBtn').addEventListener('click', function() {
  const output = document.getElementById('prefsOutput');
  const saved = localStorage.getItem('userPreferences');

  if (saved !== null) {
    const preferences = JSON.parse(saved);

    document.getElementById('darkMode').checked = preferences.darkMode;
    document.getElementById('notifications').checked = preferences.notifications;
    document.getElementById('language').value = preferences.language;

    output.className = 'success';
    output.textContent = '✓ Preferences loaded!\n' +
      JSON.stringify(preferences, null, 2);
  } else {
    output.textContent = 'No saved preferences found.';
  }
});

// Example 3: View All Storage
document.getElementById('viewAllBtn').addEventListener('click', function() {
  const output = document.getElementById('allOutput');

  if (localStorage.length === 0) {
    output.textContent = 'No data in localStorage';
    return;
  }

  output.className = 'info';
  output.innerHTML = `<strong>Total items: ${localStorage.length}</strong><br><br>`;

  for (let i = 0; i < localStorage.length; i++) {
    const key = localStorage.key(i);
    const value = localStorage.getItem(key);

    output.innerHTML += `<strong>${key}:</strong> ${value}<br>`;
  }
});

document.getElementById('clearAllBtn').addEventListener('click', function() {
  if (confirm('Are you sure you want to clear all localStorage data?')) {
    localStorage.clear();

    const output = document.getElementById('allOutput');
    output.className = 'success';
    output.textContent = '✓ All localStorage data cleared!';

    // Reset form
    document.getElementById('key').value = '';
    document.getElementById('value').value = '';
    document.getElementById('simpleOutput').textContent = '';
    document.getElementById('prefsOutput').textContent = '';
  }
});

// Load preferences on page load (if they exist)
window.addEventListener('load', function() {
  const saved = localStorage.getItem('userPreferences');
  if (saved) {
    const preferences = JSON.parse(saved);
    document.getElementById('darkMode').checked = preferences.darkMode;
    document.getElementById('notifications').checked = preferences.notifications;
    document.getElementById('language').value = preferences.language;
  }
});
Notes
  • Storage Limits: Most browsers allow 5-10MB per domain. Exceeding this will throw a QuotaExceededError.
  • Security: Don't store sensitive data (passwords, credit cards) in localStorage - it's not encrypted and accessible via JavaScript.
  • sessionStorage: Similar API but data only lasts for the browser session - cleared when tab/window is closed.