SyntaxStudy
Sign Up
JavaScript Beginner 4 min read

localStorage Basics

localStorage

localStorage stores data that persists even when the browser is closed. Data is per-origin and not shared between tabs on different origins.

Example
// Store values
localStorage.setItem("theme", "dark");
localStorage.setItem("lang", "en");

// Retrieve values
const theme = localStorage.getItem("theme"); // "dark"
const missing = localStorage.getItem("nope"); // null

// Remove a specific key
localStorage.removeItem("theme");

// Clear all keys for this origin
localStorage.clear();

// Count items
console.log(localStorage.length); // Number of stored items
Pro Tip

localStorage.getItem() returns null (not undefined) for missing keys — test with !== null, not != null.