Summary - Local storage
Build an app that saves and restores a dark-mode preference using localStorage and JSON.
Summary - Local storage
In this group you learned to store data with localStorage and sessionStorage. localStorage is persistent; sessionStorage is cleared when the tab closes. Both store only text; you turn arrays and objects into text with join and split and read them back.
For clearing, removeItem deletes one key and clear deletes all. To react to changes in another tab, you listen for the storage event. Now you will build an app that brings these together.
Exercise Save and read a dark-mode preference
Save the value 'dark' under the 'theme' key with setItem. Then read it with getItem; set isDark to true if the value is 'dark', otherwise false.
Show example solution
localStorage.setItem('theme', 'dark');
const saved = localStorage.getItem('theme');
const isDark = saved === 'dark';
Exercise Delete the preference and read it back
Delete the 'theme' key with removeItem. Then read it again with getItem and assign the result to a theme variable.
Show example solution
localStorage.removeItem('theme');
const theme = localStorage.getItem('theme');
Test yourself
-
Which storage type survives a browser restart?
localStorage.setItem('a', '1'); sessionStorage.setItem('b', '2');- sessionStorage
- localStorage
- windowStorage
- tempStorage
Show answer
localStorage — Correct! localStorage survives a browser restart.
-
Match all the methods
- setItem(k, v)
- Saves the value
- getItem(k)
- Reads the value
- removeItem(k)
- Deletes one key
- clear()
- Deletes everything