The Web Storage API
The complete API
Section titled “The complete API”Both localStorage and sessionStorage implement the same Storage interface. Every method and property below applies to both — just swap the object name.
setItem(key, value)
Section titled “setItem(key, value)”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'getItem(key)
Section titled “getItem(key)”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'); // nullAlways guard against null before using the returned value.
removeItem(key)
Section titled “removeItem(key)”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')); // nullclear()
Section titled “clear()”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); // 0key(index)
Section titled “key(index)”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 varieslength
Section titled “length”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));}Runnable: the full API in action
Section titled “Runnable: the full API in action”Reading a missing key returns null
Section titled “Reading a missing key returns null”This is one of the most common bugs with Web Storage: confusing null with a stored value.
// Nothing stored yetconst val = localStorage.getItem('demo:nonexistent');console.log(val); // nullconsole.log(val === null); // true — use === null check, not falsy !valBe 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”.
Iterating all keys
Section titled “Iterating all keys”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 uplocalStorage.removeItem('demo:one');localStorage.removeItem('demo:two');