Clearing storage
Learn to clear storage with removeItem and clear.
Deleting one key with removeItem
To delete a single key, use the removeItem method. Other keys are not affected; only the key you name is removed.
localStorage.removeItem('old_data');If the key was never saved, nothing happens; no error is thrown. So you do not need to check with getItem before removing.
Emptying the whole store with clear
To empty the whole store at once, call the clear method. It deletes every key in that store and saves you from calling removeItem one by one.
localStorage.clear();Be careful: clear is not selective and you cannot undo it. Make sure you really want to delete all data before calling it. If you only want to remove a few keys, use removeItem.
Exercise Clear one key and the whole store
First delete the 'temp' key with removeItem. Then clear all of localStorage with clear.
Show example solution
localStorage.removeItem('temp');
localStorage.clear();
Test yourself
-
You want to delete only one key. Which method do you use?
// ? localStorage.____('temp');- clear
- removeItem
- delete
- destroy
Show answer
removeItem — Correct! removeItem deletes a single key.
-
Delete the old_data key
localStorage.____('old_data');Show answer
localStorage.removeItem('old_data'); -
Match methods to their effects
- removeItem('a')
- Deletes only the 'a' key
- clear()
- Deletes all keys
- getItem('a')
- Does not delete, only reads
-
What happens if you removeItem a key that does not exist?
localStorage.removeItem('never_saved');- It throws
- It returns false
- Nothing happens, no error
- The whole store is cleared
Show answer
Nothing happens, no error — Correct! Removing a missing key silently does nothing.