You choose the dark theme on your favourite site, then refresh the page. The site is light again. The reason: every JavaScript variable is gone as soon as the page is refreshed, so your choice is gone too.
To keep a choice like the theme, the browser has localStorage: a small storage space in the browser. Data that you save in localStorage stays there even when the page is refreshed, the tab is closed, or the browser is opened again the next day. localStorage is good for small things, such as a theme choice or a click count.
Save and read with setItem and getItem
The example below saves the number 17, then reads it back:
localStorage.setItem('age', 17)
const age = localStorage.getItem('age')
console.log(typeof age, age) // string 17
localStorage.setItem('age', 17)saves the value17under the name'age'. That name is called a key. Think of localStorage as a cabinet of drawers: the key is the label on a drawer, and the value is what is inside that drawer. Later you take the contents out with the same label.localStorage.getItem('age')reads what is in the drawer labelled'age'and returns it.typeof ageisstring. localStorage only stores text, so the number17comes back as the text"17".
If a key was never saved, getItem returns null. For example, localStorage.getItem('missing') gives null.
To delete data, localStorage.removeItem('age') removes one key, and localStorage.clear() removes every key.
A number that survives a refresh
The most common pattern: read the saved number as soon as the page opens, show that number, then save it again on every click. The code below uses that pattern to count clicks on a like button:
const button = document.querySelector('button')
const text = document.querySelector('#likes')
let likes = Number(localStorage.getItem('likes') || 0)
text.textContent = likes
button.addEventListener('click', () => {
likes = likes + 1
localStorage.setItem('likes', likes)
text.textContent = likes
})
localStorage.getItem('likes') || 0: the first time the page opens, the key'likes'does not exist yet, sogetItemreturnsnull, and the value on the right of||is used, which is0.Number(...)turns text into a number, for example'3'into3. WithoutNumber,'3' + 1joins the two as text and gives'31'.text.textContent = likesis written beforeaddEventListener. So the saved number shows as soon as the page opens, not only after the first click.- Inside the listener there are three steps: add 1, save again with
setItem, then show the number. localStorage does not change by itself when the variablelikeschanges. That is why you callsetItemevery timelikeschanges.
Refresh the page: the number continues from the last number and does not go back to 0.
Objects are saved as JSON
localStorage only stores text, so an object must first be turned into JSON text:
const user = { name: 'Budi', level: 3 }
localStorage.setItem('user', JSON.stringify(user))
const saved = JSON.parse(localStorage.getItem('user'))
console.log(saved.name) // Budi
Without JSON.stringify, the object is saved as the text '[object Object]' and its contents are lost. So save with JSON.stringify, then read back with JSON.parse.
⚠️ localStorage limits people forget
- Secret data in localStorage. Every script on your page can read what is in localStorage. So never keep passwords or login tokens (proof that you are logged in) here.
- Expecting the data on another device. The data in localStorage is saved only in one browser, for one site. If you open the site on your phone or in another browser, localStorage is empty there.
JSON.parseon a key that isn't there.getItemreturnsnull, andJSON.parse(null)givesnull, not an error. But readingsaved.nameafter that causes an error, becausenullhas no properties. Check the result before you read from it.- The space is small. Each site gets only about 5 MB. When it is full,
setItemfails with aQuotaExceededError.
💡 Its twin:
sessionStorage.sessionStoragehas exactly the same methods as localStorage (setItem,getItem,removeItem,clear). The difference: what is insessionStorageis gone once the tab closes. It is good for a form that is only half filled in.
TL;DR: localStorage is a small storage space in the browser. What you save there stays even when the page is refreshed. localStorage.setItem(key, value) saves a value under a name (the key), and localStorage.getItem(key) reads it. A key that isn't there gives null. The contents of localStorage are always text. So read numbers back with Number(...), save objects with JSON.stringify, and read objects back with JSON.parse. When the page opens, read and show the saved data, then call setItem again every time the value changes. Never keep secret data in localStorage.
⚡ Save it, then read it back
Write:
localStorage.setItem('age', 17)
const age = localStorage.getItem('age')
console.log(typeof age, age) // ?
Guess first: this code saves 17 in the browser, then reads it back. What gets printed?
string 17. localStorage only stores text, so the number 17 comes back as the text "17".
Meaning: localStorage is a small storage space in the browser. setItem saves a value under the name (key) 'age', and getItem reads it back with the same key. A key that was never saved gives null. The data stays even when the page is refreshed.
⚡ Turn it back into a number
Write:
let likes = Number(localStorage.getItem('likes') || 0)
Meaning: When the page opens, this line reads the saved number of likes. The first time, the key 'likes' does not exist yet, so getItem returns null, and || 0 replaces it with 0. Number(...) turns the text into a number, because without Number, '3' + 1 becomes '31'. Every time likes changes, save it again with setItem.
⚡ Objects go through JSON
Write:
localStorage.setItem('user', JSON.stringify(user))
const saved = JSON.parse(localStorage.getItem('user'))
Meaning: localStorage only stores text. Without JSON.stringify, the object user is saved as the text '[object Object]' and its contents are lost. Read it back with JSON.parse. Never keep passwords or login tokens (proof that you are logged in) in localStorage, because every script on your page can read them.