By the end of this lesson, you will be able to store and retrieve simple client-side data using localStorage and sessionStorage, and choose the right one for the job.
What it is
The Web Storage API gives JavaScript two built-in storage objects: localStorage and sessionStorage. Both store key/value pairs for one origin, meaning the same protocol, host, and port. Values are always strings, so numbers, booleans, arrays, and objects must be converted before saving.
localStorage persists until the user or site clears it, and it is shared across tabs from the same origin. sessionStorage lasts only for the current browser tab or window session; closing that tab clears it. Related terms include key, value, origin, quota, and the storage event, which fires in other same-origin tabs when localStorage changes.
Why it matters
- It lets you save user preferences, such as theme or language, without a server.
- It can preserve form drafts or wizard progress during a session.
- It is simpler than cookies for client-only data because it is not sent with every HTTP request.
- It supports basic cross-tab communication through the
storageevent. - It helps build offline-friendly interfaces for small amounts of data.
Syntax or steps
The smallest useful pattern is setItem and getItem.
- Call
setItem(key, value)to save a string. - Call
getItem(key)to read it; it returnsnullif the key is missing. - Call
removeItem(key)to delete one key. - Call
clear()to remove all keys for that storage type and origin. - Use
lengthandkey(index)to inspect stored keys.
Example
const prefs = { theme: "dark", fontSize: 14 };
// localStorage persists across browser sessions
localStorage.setItem("prefs", JSON.stringify(prefs));
// sessionStorage lasts for the current tab/session
sessionStorage.setItem("wizardStep", "2");
const saved = JSON.parse(localStorage.getItem("prefs") || "{}");
console.log(saved.theme);
localStorage.removeItem("prefs");
sessionStorage.clear();
Part-by-part explanation
JSON.stringify(prefs)converts an object into a string because storage only accepts strings.localStorage.setItem("prefs", ...)saves the string under the keyprefs.sessionStorage.setItem("wizardStep", "2")saves temporary tab data.localStorage.getItem("prefs") || "{}"provides a safe fallback if the key is missing.JSON.parse(...)converts the stored string back into an object.removeItemdeletes one key, whilecleardeletes all keys in that storage area.
Common mistakes
- Storing objects directly. Fix it by using
JSON.stringifyandJSON.parse. - Assuming values keep their type. A number saved as
42comes back as"42". - Confusing persistence. Use
localStoragefor long-term data andsessionStoragefor temporary tab data. - Ignoring failures. Storage can be full, disabled, or restricted in private browsing; wrap calls in
try/catchwhen needed.
When to use it
Use Web Storage for client-side data that does not need to be sent to the server. Use cookies when the server must read the value, such as session tokens or server-rendered preferences.
| Option | Lifetime | Best for |
|---|---|---|
localStorage | Persists until cleared | Theme, language, small saved drafts |
sessionStorage | Current tab only | Wizard steps, temporary form state |
| Cookies | Configurable, sent to server | Server-readable session data |
Practice
Guided exercise
Save the user’s theme as "dark" in localStorage, then read it and log it.
Expected output: dark
Challenge
Store an array of recent searches in localStorage, then retrieve and log the first item.
Solution hint: use JSON.stringify to save the array and JSON.parse to read it.
Quick check
Question: Which storage type should you use for data that must survive closing and reopening the browser?
Answer: localStorage.
Summary
Web Storage gives JavaScript simple key/value storage for the current origin. Choose localStorage for persistent client data and sessionStorage for temporary tab data, and remember that values are strings unless you serialize them yourself.