Home/Blog/LocalStorage in JavaScript - Complete Guide with Real Examples
Tutorial

LocalStorage in JavaScript - Complete Guide with Real Examples

Master localStorage in JavaScript with this complete guide. Learn how to persist data in the browser with practical examples from real projects.

A
Ashwani
Author
📅Dec 10, 2024
⏱️7 min read
#javascript#tutorial#localStorage#web-api#browser-storage

LocalStorage in JavaScript - Complete Guide

LocalStorage is one of the most useful browser APIs for storing data on the client side. Let's learn how to use it effectively.

What is LocalStorage?

LocalStorage allows you to store key-value pairs in the browser that persist even after the page is closed.

Key features:

  • •Storage limit: ~5-10MB per domain
  • •Stores only strings
  • •Synchronous API
  • •No expiration time
  • •Accessible only from same origin

Basic Operations

1. Storing Data

javascript
// Store a string
localStorage.setItem('username', 'John');

// Store a number (will be converted to string)
localStorage.setItem('age', 25);

// Store an object (must stringify first)
const user = { name: 'John', age: 25 };
localStorage.setItem('user', JSON.stringify(user));

2. Retrieving Data

javascript
// Get a string
const username = localStorage.getItem('username');

// Get and parse an object
const userString = localStorage.getItem('user');
const user = JSON.parse(userString);

3. Removing Data

javascript
// Remove a specific item
localStorage.removeItem('username');

// Clear all localStorage
localStorage.clear();

4. Checking if Key Exists

javascript
if (localStorage.getItem('username')) {
  console.log('Username exists');
}

// Or check all keys
const hasUser = Object.keys(localStorage).includes('username');

Real-World Examples

Example 1: Dark Mode Preference

javascript
// Save dark mode preference
function toggleDarkMode() {
  const isDark = document.body.classList.toggle('dark-mode');
  localStorage.setItem('darkMode', isDark);
}

// Load dark mode on page load
window.addEventListener('DOMContentLoaded', () => {
  const isDark = localStorage.getItem('darkMode') === 'true';
  if (isDark) {
    document.body.classList.add('dark-mode');
  }
});

Example 2: Todo List Persistence

javascript
// Save todos array
function saveTodos(todos) {
  localStorage.setItem('todos', JSON.stringify(todos));
}

// Load todos on app start
function loadTodos() {
  const todosString = localStorage.getItem('todos');
  return todosString ? JSON.parse(todosString) : [];
}

// Usage
let todos = loadTodos();

Example 3: Form Data Auto-save

javascript
// Auto-save form input
const input = document.getElementById('email');
input.addEventListener('input', (e) => {
  localStorage.setItem('draft_email', e.target.value);
});

// Restore on page load
window.addEventListener('DOMContentLoaded', () => {
  const draft = localStorage.getItem('draft_email');
  if (draft) {
    input.value = draft;
  }
});

Best Practices

1. Always Handle Errors

javascript
function safeSetItem(key, value) {
  try {
    localStorage.setItem(key, value);
    return true;
  } catch (e) {
    if (e.name === 'QuotaExceededError') {
      console.error('Storage quota exceeded');
    }
    return false;
  }
}

2. Use Helper Functions

javascript
const storage = {
  set(key, value) {
    try {
      localStorage.setItem(key, JSON.stringify(value));
      return true;
    } catch (e) {
      return false;
    }
  },

  get(key, defaultValue = null) {
    try {
      const item = localStorage.getItem(key);
      return item ? JSON.parse(item) : defaultValue;
    } catch (e) {
      return defaultValue;
    }
  },

  remove(key) {
    localStorage.removeItem(key);
  },

  clear() {
    localStorage.clear();
  }
};

// Usage
storage.set('user', { name: 'John' });
const user = storage.get('user');

3. Namespace Your Keys

javascript
// Bad
localStorage.setItem('todos', '[]');
localStorage.setItem('settings', '{}');

// Good - prefix with app name
localStorage.setItem('myapp_todos', '[]');
localStorage.setItem('myapp_settings', '{}');

Common Pitfalls

❌ Not Checking for Browser Support

javascript
// Always check first
if (typeof Storage !== 'undefined') {
  localStorage.setItem('key', 'value');
} else {
  console.log('LocalStorage not supported');
}

❌ Storing Sensitive Data

Never store:

  • •Passwords
  • •Credit card numbers
  • •API keys
  • •Personal identification

❌ Forgetting to Parse JSON

javascript
// Wrong
const todos = localStorage.getItem('todos');
todos.push(newTodo); // Error! todos is a string

// Correct
const todos = JSON.parse(localStorage.getItem('todos'));
todos.push(newTodo);

LocalStorage vs SessionStorage vs Cookies

| Feature | LocalStorage | SessionStorage | Cookies |

|---------|-------------|----------------|---------|

| Capacity | ~5-10MB | ~5-10MB | ~4KB |

| Expiration | Never | Tab close | Configurable |

| Sent to server | No | No | Yes |

| Accessible from | JavaScript | JavaScript | JS & Server |

Projects Using LocalStorage

See localStorage in action:

Further Reading

Start building projects with localStorage today! 🚀

Found this helpful?

Share this article with your developer friends!

📚Continue Learning

Explore more tutorials and guides

Guide
⭐ Featured

50+ JavaScript Interview Questions & Answers (2026) — Beginner to Advanced

📅Feb 18, 2026
⏱️25 min read

50+ most asked JavaScript interview questions with clear, detailed answers. From beginner basics to advanced concepts like closures, event loop, prototypes, and async patterns — everything you need to crack your next JS interview.

#javascript#interview#interview-questions+8
A
Ashwani
Read More→
Tutorial
⭐ Featured

How to Build a Weather App in JavaScript - Complete Fetch API Tutorial

📅Feb 18, 2026
⏱️18 min read

Build a real-time Weather App with JavaScript from scratch. Learn the Fetch API, async/await error handling, Geolocation API, and how to integrate OpenWeatherMap in this complete step-by-step tutorial.

#javascript#fetch-api#weather-app+6
A
Ashwani
Read More→
Tutorial

DOM Manipulation JavaScript Hindi: Complete Guide with Real Examples

📅Jan 21, 2026
⏱️22 min read

DOM Manipulation JavaScript ka sabse important concept hai! Is guide mein seekho getElementById, querySelector, createElement, Events - sab kuch Hindi mein real examples ke saath.

#javascript#dom#dom-manipulation+7
A
Ashwani
Read More→