JAVASCRIPT

JavaScript Local Storage: Syntax, Usage, and Examples

JavaScript local storage lets you store key-value pairs in a user's browser with no expiration time. Data remains even after the page reloads or the browser closes, making it useful for saving user preferences and application state.

Quick Answer: How to Use Local Storage in JavaScript

Local Storage provides a way to save key-value pairs in a web browser that persist even after the browser is closed. All data is stored as strings. To store objects or arrays, you must first convert them to a JSON string using JSON.stringify().

Basic Methods:

  • localStorage.setItem(key, value): Save a key-value pair.
  • localStorage.getItem(key): Retrieve the value for a given key.
  • localStorage.removeItem(key): Remove a specific key-value pair.
  • localStorage.clear(): Remove all items.

Example:

// Storing a string
localStorage.setItem('theme', 'dark');

// Storing an object (requires JSON.stringify)
const user = { name: 'Alice', loggedIn: true };
localStorage.setItem('user', JSON.stringify(user));

// Retrieving and parsing the data
const savedTheme = localStorage.getItem('theme'); // 'dark'
const savedUser = JSON.parse(localStorage.getItem('user')); // { name: 'Alice', loggedIn: true }

console.log(savedTheme);
console.log(savedUser.name); // 'Alice'

// Removing an item
localStorage.removeItem('theme');

How to Use Local Storage in JavaScript

Local storage provides methods to store, retrieve, update, and remove data.

Basic Syntax

// Save data
localStorage.setItem("username", "Alice");

// Retrieve data
let username = localStorage.getItem("username");

// Remove data
localStorage.removeItem("username");

// Clear all data
localStorage.clear();
  • setItem(key, value): Stores data under a key.
  • getItem(key): Retrieves stored data.
  • removeItem(key): Deletes specific data.
  • clear(): Deletes all stored data.

When to Use Local Storage in JavaScript

Use local storage when you need to store simple, persistent data on a user's device.

  1. Save user preferences like theme or language settings.
  2. Store form inputs so users don’t lose data when they refresh the page.
  3. Remember non-sensitive state such as the last opened tab or whether the sidebar is collapsed.

Examples of Local Storage in JavaScript

Storing and Retrieving User Preferences

You can store user-selected theme preferences.

localStorage.setItem("theme", "dark");

let theme = localStorage.getItem("theme");
console.log("Current theme:", theme);

Storing Objects in Local Storage

Local storage only supports strings. Convert objects to JSON with JSON.stringify() before storing them.

let user = { name: "Alice", age: 30 };
localStorage.setItem("user", JSON.stringify(user));

// Retrieve and parse data
let retrievedUser = JSON.parse(localStorage.getItem("user"));
console.log("User:", retrievedUser);

Removing and Resetting Local Storage

To remove a specific item:

localStorage.removeItem("user");

To reset everything:

localStorage.clear();

Learn More About Local Storage in JavaScript

Checking if Local Storage is Available

Not all browsers support local storage. Check before using it.

if (typeof Storage !== "undefined") {
  console.log("Local storage is available");
} else {
  console.log("Local storage is not supported");
}

Handling Expiration in Local Storage

Local storage does not have built-in expiration. You need to implement it manually.

let now = new Date().getTime();
let expiry = now + 1000 * 60 * 60; // Expires in 1 hour
localStorage.setItem("expiryTime", expiry);

// Check expiration
if (new Date().getTime() > localStorage.getItem("expiryTime")) {
  localStorage.removeItem("expiryTime");
  console.log("Stored data expired");
}

Clearing Local Storage on Logout

When logging out a user, clearing local storage removes sensitive data.

function logout() {
  localStorage.clear();
  console.log("User logged out, local storage cleared");
}

Adding and Removing Items Dynamically

You can store lists and update them dynamically.

let tasks = JSON.parse(localStorage.getItem("tasks")) || [];

tasks.push("Finish project");
localStorage.setItem("tasks", JSON.stringify(tasks));

console.log("Tasks:", JSON.parse(localStorage.getItem("tasks")));

Accessing Local Storage in JavaScript

Accessing stored data is simple.

let savedData = localStorage.getItem("username");
console.log("Saved username:", savedData);

Using Local Storage in a To-Do List

Local storage helps maintain a to-do list across sessions.

function addTask(task) {
  let tasks = JSON.parse(localStorage.getItem("tasks")) || [];
  tasks.push(task);
  localStorage.setItem("tasks", JSON.stringify(tasks));
}

function getTasks() {
  return JSON.parse(localStorage.getItem("tasks")) || [];
}

addTask("Buy groceries");
console.log("Current tasks:", getTasks());

Comparing Local Storage with Session Storage

Both store data in the browser, but session storage clears data when the tab closes.

sessionStorage.setItem("sessionKey", "sessionValue");
console.log(sessionStorage.getItem("sessionKey")); // Data removed after closing tab

Handling Large Data in Local Storage

Local storage has a 5MB limit per domain. Store large datasets on a server instead of local storage.

Key Takeaways for JavaScript Local Storage

  • Persistent Storage: Data in Local Storage remains even after the user closes the browser and reopens it. It has no automatic expiration.
  • String-Only: Local Storage can only store strings. To store complex data like objects or arrays, you must first convert them to a JSON string with JSON.stringify() and then parse them back with JSON.parse() upon retrieval.
  • Synchronous API: All Local Storage operations (setItem, getItem, etc.) are synchronous, meaning they can block the main browser thread if used excessively.
  • Domain-Specific: Data is specific to the protocol, hostname, and port of the website. A site on http:// cannot access storage from the same site on https://.
  • Not for Sensitive Data: Local Storage is not a secure place to store sensitive information like passwords or personal details, as it is easily accessible via JavaScript on the client side.