Skip to content

The Web Storage API

Both localStorage and sessionStorage implement the same Storage interface. Every method and property below applies to both — just swap the object name.

Stores a string value under a string key. If the key already exists the value is overwritten (there is no separate “update” method).

localStorage.setItem('demo:theme', 'dark');
localStorage.setItem('demo:theme', 'light'); // overwrites — now 'light'

Returns the stored string for the given key, or null (not undefined) if the key does not exist.

const theme = localStorage.getItem('demo:theme'); // 'light'
const missing = localStorage.getItem('demo:nope'); // null

Always guard against null before using the returned value.

Deletes a single key/value pair. Calling it on a key that does not exist is a no-op — no error is thrown.

localStorage.removeItem('demo:theme');
console.log(localStorage.getItem('demo:theme')); // null

Deletes all key/value pairs in the store for the current origin. Use with caution on localStorage — it wipes every key set by every script on the origin.

localStorage.clear();
console.log(localStorage.length); // 0

Returns the key name at the given numeric index (0-based), or null if the index is out of range. The ordering is not guaranteed to be insertion order — treat it as implementation-defined.

localStorage.setItem('demo:a', '1');
localStorage.setItem('demo:b', '2');
console.log(localStorage.key(0)); // 'demo:a' or 'demo:b' — order varies

A read-only property that returns the number of key/value pairs currently stored. Use it to iterate all keys:

for (let i = 0; i < localStorage.length; i++) {
const k = localStorage.key(i);
console.log(k, localStorage.getItem(k));
}
Browser Storage

This is one of the most common bugs with Web Storage: confusing null with a stored value.

// Nothing stored yet
const val = localStorage.getItem('demo:nonexistent');
console.log(val); // null
console.log(val === null); // true — use === null check, not falsy !val

Be careful: the string "null" is a valid stored value that is truthy. Always use === null rather than !val to distinguish “key absent” from “key present with an empty or falsy value”.

localStorage.setItem('demo:one', '1');
localStorage.setItem('demo:two', '2');
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
console.log(key, '->', localStorage.getItem(key));
}
// Clean up
localStorage.removeItem('demo:one');
localStorage.removeItem('demo:two');
What does localStorage.getItem("missing-key") return when the key has never been set?
You call localStorage.setItem("x", "first") then localStorage.setItem("x", "second"). What is the stored value?
What does localStorage.key(index) return when index is out of range?
Which method removes ALL key/value pairs in localStorage for the current origin?