localStorage basics
Learn to store persistent key-value pairs in the browser with localStorage.
What is localStorage?
localStorage is a persistent store in the browser that holds key-value pairs. Data you save survives page reloads and browser restarts; it is removed only when you delete it with JavaScript or the user clears it.
To save a value, use the setItem method: it takes two string parameters, a key and a value.
localStorage.setItem('theme', 'dark');This line stores 'dark' under the 'theme' key. Writing the same key again overwrites the previous value.
Reading with getItem
To read the data you saved, use the getItem method. You pass the key as a parameter; the method returns the value for that key as a string.
const theme = localStorage.getItem('theme');If the key was never saved, getItem returns null. So it is a good habit to check for null before using the value.
Exercise Save a city and read it back
Save the value 'Berlin' under the 'city' key with setItem. Then read it back into a city variable with getItem.
Show example solution
localStorage.setItem('city', 'Berlin');
const city = localStorage.getItem('city');
Test yourself
-
Which saves 'tr' under the 'lang' key?
// A localStorage.set('lang', 'tr'); // B localStorage.setItem('lang', 'tr'); // C localStorage.save('lang', 'tr'); // D localStorage.put('lang', 'tr');- A
- B
- C
- D
Show answer
B — Correct! setItem takes two parameters: key and value.
-
Read the saved theme
const theme = localStorage.____('theme');Show answer
const theme = localStorage.getItem('theme'); -
Match methods to their meanings
- localStorage.setItem(k, v)
- Saves the value
- localStorage.getItem(k)
- Reads value, else null
- localStorage.removeItem(k)
- Deletes the key
-
What does getItem return for a key that was never saved?
localStorage.getItem('missing');- null
- undefined
- Empty string: ''
- It throws
Show answer
null — Correct! getItem returns null for a missing key.