localStorage (JavaScript)

localStorage lets a website save key/value data in the browser that persists even after the page is closed. Values are always stored as strings.

JavaScript

Use localStorage.setItem() to save data and getItem() to read it back. Because everything is stored as text, you usually JSON.stringify objects before saving and JSON.parse them after loading.

Data stays until the user clears it or your code removes it, making it useful for preferences and saved progress.

Syntax

localStorage.setItem(key, value)  /  localStorage.getItem(key)

Examples

JavaScript

localStorage.setItem("theme", "dark");
const theme = localStorage.getItem("theme");
console.log(theme);

Output:

dark

See also

Back to the Dictionary