JavaScript: localStorage (In-Depth)

localStorage is a Web Storage API that allows JavaScript to store key-value pairs in a user's browser. Data in localStorage persists even after the page is closed or reloaded, until it is explicitly cleared.

Basic Usage

localStorage.setItem("name", "Alice");
let name = localStorage.getItem("name"); // "Alice"
localStorage.removeItem("name");
localStorage.clear(); // Removes all keys
    

All Data is Stored as Strings

localStorage.setItem("age", 25);
typeof localStorage.getItem("age"); // "string"
    
Tip: Use JSON.stringify() and JSON.parse() to store/retrieve objects or arrays.
const user = { name: "Rafi", age: 30 };
localStorage.setItem("user", JSON.stringify(user));
// ...
const data = JSON.parse(localStorage.getItem("user"));
// { name: "Rafi", age: 30 }
    

When to Use localStorage

Limitations and Security

Practice: Try saving and retrieving objects and arrays, and clear the storage from the browser console to see the effect.