JavaScript - how to use localStorage
In this article, we would like to show you how to use localStorage in JavaScript.
1. Overview
TheĀ localStorage
Ā stores data permanently. Once saved data is already there and the application can refer to it at any time, regardless of the session, unless the user manually deletes the contents ofĀ localStorage
.Ā There is also no built-in mechanism that would say how long data can be stored inĀ localStorage
Ā (as e.g. in the case of cookies).
The localStorage extends Storage that can store key/value (property/value) pairs and has built-in methods (like .length
, .key( )
, etc.).
2. View localStorage in web browser (Google Chrome)
In order to view items stored in the localStorage:
- Open developer tools (
F12
orCtrl
+Shift
+I
), - Go to the Application tab,
- from the Storage section in the menu on the left select Local Storage.
Now you can view sites and items they store in the localStorage.
Example view on items stored by dirask:

3. store value in localStorage
To put items into the localStorage we use setItem()
method that takes two arguments: key and value.
// ONLINE-RUNNER:browser;
window.localStorage.setItem('itemKey', 'itemValue');
Now you can see the item in the developer tools:

To store arrays or objects, you haveĀ to convert them to strings.
// ONLINE-RUNNER:browser;
const item = {
key: 'itemKey',
value: 'itemValue',
}
window.localStorage.setItem('item', JSON.stringify(item));
4. get itemĀ from localStorage
To get items from localStorage, we use getItem()
method that takes the item key (name) as an argument.
// ONLINE-RUNNER:browser;
var item = window.localStorage.getItem('itemKey');
console.log(item); // Output: itemValue
To get an object created converted to string withĀ JSON.stringify()
, you need to parse it back using JSON.parse()
method.
// ONLINE-RUNNER:browser;
var item = window.localStorage.getItem('item');
console.log(item); // Output: {"key":"itemKey","value":"itemValue"}
5. remove itemĀ from localStorage
To remove items fromĀ localStorage, we use removeItem()
method that takes the item key as an argument andĀ removes that key from the storage if it exists. If there is no item with the given key, theĀ method will do nothing.
// ONLINE-RUNNER:browser;
window.localStorage.removeItem('itemKey');
6. clear localStorage
To clear the entire localStorage, we use clear()
method that takes no arguments and clears the entire storage of all records for theĀ domain.
// ONLINE-RUNNER:browser;
window.localStorage.clear();
Ā