The localStorage
and sessionStorage
objects, part of the web storage API, are two great tools for saving key/value pairs locally. Using localStorage
and sessionStorage
for storage is an alternative to using cookies and there are some advantages:
It’s also supported in all modern browsers, so you can use it today without an issue. Cookies are still useful, especially when it comes to authentication, but there are times when using localStorage
or sessionStorage
may be a better alternative.
To complete this tutorial, you will need the following:
localStorage
vs sessionStorage
localStorage
and sessionStorage
are almost identical and have the same API. The difference is that with sessionStorage
, the data is persisted only until the window or tab is closed. With localStorage
, the data is persisted until the user manually clears the browser cache or until your web app clears the data. This tutorial features localStorage
, but the syntax for sessionStorage
is the same.
With this knowledge, you can now create, read, and update key/value pairs in localStorage
.
You can create entries for the localStorage
object by using the setItem()
method. The setItem()
method takes two arguments, the key
and corresponding value:
let key = 'Item 1';
localStorage.setItem(key, 'Value');
To read entries, use the getItem()
method. The getItem()
method takes one argument which must be the key. This function will return the corresponding value as a string:
let myItem = localStorage.getItem(key);
This code sets myItem
equal to 'Value'
, which is the corresponding value for key
.
Updating an entry is done with the setItem()
method. Again, it takes two arguments. The key argument will be an existing key while the value argument will be a new value:
localStorage.setItem(key, 'New Value');
Now, the localStorage
value for key
is 'New Value'
instead of 'Value'
.
You can create, read, and update entries in the localStorage
object. You can also delete individual entries and clear all entries in localStorage
.
You can delete an entry with the removeItem()
method. The removeItem()
method takes one argument which will be a key of the localStorage
object:
localStorage.removeItem(key);
You can also clear all items in localStorage
. This can be done with the clear()
method:
Here’s how to clear everything that’s stored in localStorage
:
localStorage.clear();
These methods give you more the ability to remove and clear items from localStorage
quickly. There are some limits to localStorage
, though. Both localStorage
and sessionStorage
can only store strings. To work around this, you will have to use JSON methods.
localStorage
can only store string values. If you want to store objects or arrays as values in localStorage
, you can use JSON.stringify()
to convert them into strings. When creating or updating key/value pairs in localStorage
, use JSON.stringify()
with the object or array as the argument:
let myObj = { name: 'Skip', breed: 'Labrador' };
localStorage.setItem(key, JSON.stringify(myObj));
Although myObj
is an object, JSON.stringify(myObj)
converts it into a string. So myObj
is now a valid localStorage
value.
To read and return stringified values, use the JSON.parse()
method. The JSON.parse()
method takes JSON strings and converts them into JavaScript objects. JSON.parse()
takes .getItem()
as it’s argument:
let item = JSON.parse(localStorage.getItem(key));
Now item
is set equal to the value of key
. In the previous code snippet, the value of key
was set to the stringified version of myObj
. Using JSON.parse
converts myObj
back into an object. So item
is set equal to myObj
as an object, not a string.
Being able to convert arrays and objects into strings using JSON.stringify
and convert them back using JSON.parse
is very useful. You will also need to know how to check if localStorage
is empty or not.
In this step, you will test for the presence of items in the localStorage
. You can use if
statements to check if localStorage
is holding items or if it is empty. To do this, check the length of localStorage
:
if (localStorage.length > 0) {
// ...
}
If localStorage.length
is greater than 0
, then there are items within the localStorage
object. Include an else
statement in case there are no items in localStorage
:
if (localStorage.length > 0) {
// ...
} else {
// ...
}
You can include code to be applied in the if
and else
statements. You may want to iterate over items in localStorage
.
The localStorage
and sessionStorage
objects don’t support the forEach
method. To iterate over the items in localStorage
, use a for
loop:
for (let i = 0; i < localStorage.length; i++){
}
The key()
method takes an integer as an argument and returns the corresponding key. With a for
loop, pass i
in as the integer for key()
:
for (let i = 0; i < localStorage.length; i++){
let key = localStorage.key(i);
}
Use the getItem
method to return the corresponding value for key
:
for (let i = 0; i < localStorage.length; i++){
let key = localStorage.key(i);
let value = localStorage.getItem(key);
}
Create a console.log
statement to print both key
and value
to the screen:
for (let i = 0; i < localStorage.length; i++){
let key = localStorage.key(i);
let value = localStorage.getItem(key);
console.log(key, value);
}
The key()
is very useful for iterating through localStorage
using for
loops. Not all browsers support localStorage
.
You can test for localStorage
support by checking if it’s available on the window
object using an if
statement:
if (window.localStorage) {
// localStorage supported
}
You can also use the Can I use… website to check for localStorage
support across major browsers.
You can use the localStorage
or sessionStorage
objects to store key/value pairs. There are methods that enable you to interact with the items within localStorage
. With this tutorial, you created, removed, and updated entries within localStorage
. You also converted array and object data into strings and back using JSON methods.
At times, it may be best to use cookies instead of localStorage
or session
. What Are Cookies & How to Work With Them Using JavaScript thoroughly covers this topic and is a great next step.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Sign up for Infrastructure as a Newsletter.
Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
the only problem is I cant see the serial number in localstorage after submitting. When I pass a empty field, it stuck and throw an error.
I am trying to pass a field of serial numbers from sql to select option and save the selected serial number to local storage ,the only problem is I cant see the serial number in localstorage after submitting