localStorage
Browser storage for key-value pairs that survives page refreshes and browser restarts.
- Returns
getItem()returns the saved string ornull. The other methods returnundefined.
Example
#localStorage.setItem('theme', 'dark')
localStorage.setItem('level', 7)
console.log(localStorage.getItem('theme'))
console.log(localStorage.getItem('level'), typeof localStorage.getItem('level'))
console.log(localStorage.getItem('avatar'))
localStorage.removeItem('theme')
console.log(localStorage.getItem('theme'))dark 7 string null null
The examples on this page run inside an isolated frame where localStorage isn’t available, so this code doesn’t run in the preview. On a regular page it works fine and prints the result shown above.
Definition and usage
#localStorage lets you save small amounts of data in the browser that stay there after the tab closes and you come back to the page. Typical uses are a chosen theme, interface language, a draft form, or a logged-out user’s lesson progress.
You save data with setItem(key, value), read it with getItem(key) (returns null when the key doesn’t exist), and remove it with removeItem() or clear(). Values are always strings, so convert objects and arrays to JSON with JSON.stringify(), and parse them back with JSON.parse() after reading.
Storage is separate for each domain and usually holds around 5 MB. Every script on the page has access to it, so don’t keep passwords or tokens there. The related sessionStorage has the same methods, but clears when the tab closes.
Syntax
#localStorage.setItem(key, value)
localStorage.getItem(key)
localStorage.removeItem(key)
localStorage.clear()
localStorage.lengthParameters
#key
string
The name under which you save or read the value.value
string
The value to save. Other types get converted to a string.
More examples
#const progress = { lesson: 12, points: 340, badges: ['Start', '7-day streak'] }
localStorage.setItem('progress', JSON.stringify(progress))
const saved = JSON.parse(localStorage.getItem('progress'))
console.log(saved.points)
console.log(saved.badges)
localStorage.setItem('broken', progress)
console.log(localStorage.getItem('broken'))340 ['Start', '7-day streak'] [object Object]
In the preview localStorage isn’t available, but the code works on a regular page. The last lines show that an object saved without JSON.stringify() turns into the useless string [object Object].
function loadSettings() {
try {
return JSON.parse(localStorage.getItem('settings')) ?? { theme: 'light', sound: true }
} catch {
return { theme: 'light', sound: true }
}
}
console.log(loadSettings()){ theme: 'light', sound: true }On the first visit nothing is saved yet, so the function returns the default settings. The try...catch block also guards against corrupted data and against storage being blocked, as in the preview on this page.
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Always use
JSON.stringify()before saving objects, andJSON.parse()after reading them back. - Don’t save passwords or session tokens in
localStorage. Any script on the page can read them. - Wrap reads and writes in
try...catch. In private browsing or with site data blocked, access to storage can throw.
Related entries
#- localStorage vs sessionStoragelocalStorage and sessionStorage share the same methods, but localStorage survives closing the browser, while sessionStorage clears when the tab closes.
- sessionStorageBrowser storage for key-value pairs that works only in the current tab and disappears when it closes.
- JSON.stringify()Converts a JavaScript value, such as an object or array, into a string in JSON format.
- JSON.parse()Converts a string in JSON format into a JavaScript value, such as an object or array.
- try...catchCatches errors thrown in the try block and handles them in catch. The optional finally always runs.
- MapA collection of key-value pairs where the key can be any value and insertion order is preserved.
Spotted a mistake or missing an example? Write to us.