This content originally appeared on Telerik Blogs and was authored by Ifeoma Imoh
This article describes what localStorage is and the methods used to interact with data stored in localStorage.
While developing for the web, we are mostly exchanging data back and forth. Web storage is a method of storing data on the browser in a key-value data structure. The data might be anything from user account information, session information, configurations, etc. There are several web storage techniques, including:
sessionStorage
localStorage
sessionStorage
can be used to store data on the browser by specifying a key that will be used as an identifier for the stored data. The data stored in the sessionStorage
is only available while the tab is active and is cleared
out when the tab is closed, hence the name sessionStorage
. As a result, sessionStorage
cannot be used to persist data.
localStorage
is almost the same as sessionStorage
because they both store data with the key as the identifier and the value as the data. Another thing to note about both sessionStorage
and localStorage
is that they both store data as strings. localStorage
differs from sessionStorage
in that it persists data across sessions, even when the browser is closed, allowing us to store data on the browser for as long as we want.
How To Access the localStorage Object
We can access the localStorage
object directly from the global object like so:
storage = window.localStorage
Or we can call it without specifying the global object, which is the common way of accessing the local storage object.
localStorage
localStorage
is bound by the same-origin access policy. This means that only JavaScript code in the same origin can access data meant for that origin. As a result, we can’t have JavaScript code on google.com
that accesses
the local storage data of another website, like personalsite.com
. All origins have a local storage object assigned to them, and the contents of each localStorage
vary depending on the site.
localStorage API
localStorage
exposes some methods we can use to interact with the object for storing, retrieving and deleting items in the storage. These are the properties available:
setItem(key, value)
getItem(key)
removeItem(key)
key(index)
clear()
length
setItem(key, value)
This method is used to store/add data to the local storage. It accepts two arguments: a key and a value. The key serves as an identifier for the data we want to store, while the value is the data itself.
Calling this method again with a previously used key will update the old record with the new value instead of creating a new record with the same key, implying that all keys used are supposed to be unique. It is important to note the value will be
stored as the string representation of the object passed to this method. If you pass any non-string data to the function, the value will be the result of performing String(object)
on it.
var a = [1, 2, 3]
localStorage.setItem("array", a)
var myArray = localStorage.getItem("array")
console.log(myArray) // "1, 2, 3"
As seen in the example above, the setItem()
method accepts a key and a value and stores the value as its string equivalent, which is the result of coercing (converting) an object to a string.
Another thing to keep in mind is that if you have multiple tabs or windows open for the same site, any changes in localStorage
on the active tab will be reflected on the other tabs and windows.
getItem(key)
The getItem()
method retrieves stored data. If you pass a valid key to the method, it will return the data; if the key does not exist, null
will be returned.
localStorage.setItem("name", "Ifeoma")
var name = localStorage.getItem("name")
console.log(name) // "Ifeoma"
var age = localStorage.getItem("age")
console.log(age) // null
In the first example, we added some data to our localStorage with the key name
and the value Ifeoma
. After that, we retrieve the data by passing the key name
to the getItem()
method, and the associated
value is returned—when we log, we get Ifeoma
. In the second example, we attempted to get data with the key age
, which doesn’t exist because we didn’t create it, so null
is returned when
we log age
to the console.
We’ve seen how to access the values in local storage using getItem(key)
, but there is a more direct way to do it using the dot syntax.
localStorage.setItem("name", "Ifeoma")
console.log(localStorage.name) // "Ifeoma"
The limitation of using this syntax is that the key must exist in the local storage; otherwise, undefined
is returned.
removeItem(key)
We use this method to remove data from localStorage
. To use this method, pass in the key of the data you want to remove, and both the key and the value will be removed from localStorage
.
localStorage.setItem("name", "Ifeoma")
localStorage.removeItem("name")
var item = localStorage.getItem("name")
console.log(name) // null
In the example above, we added data to localStorage
with the key name
. We then called the removeItem()
method with the key, which deletes the data from localStorage
. When we try to retrieve the data,
we get null
because the data has been deleted from the storage and the key name
is now invalid.
key(index)
The key()
method is used to access the keys stored in localStorage. The index is used to get keys, and it ranges from 0 to the length of the keys. If we have five records in localStorage, the valid indexes will be 0–4. If you enter
an invalid index, null
will be returned.
localStorage.setItem("First Name", "Ifeoma")
localStorage.setItem("Middle Name", "Sylvia")
localStorage.setItem("Last Name", "Imoh")
console.log(localStorage.key(0))
console.log(localStorage.key(1))
console.log(localStorage.key(2))
clear()
The clear()
method is used to clear out the data stored in localStorage
. Calling this method deletes all keys and values from localStorage
.
localStorage.clear()
length
The length
method retrieves the length or the number of items in localStorage
.
localStorage.setItem("First Name", "Ifeoma")
localStorage.setItem("Middle Name", "Sylvia")
console.log(localStorage.length) // 2
Storage Event
We can listen to storage changes on the browser for both localStorage
and sessionStorage
. The storage event is fired when an item is created, deleted or updated. The listener function is passed in the event with the following
properties:
- newValue: the value passed to
setItem()
when we create or update an item in storage. This value is set tonull
when we remove the item from storage. - oldValue: the value of the item previously if the key exists in the storage when creating a new item.
- key: the key of the item that is being changed, value is null if
.clear()
is called. - url: the URL for which the storage action was performed.
- storageArea: the storage object on which the action was performed (
localStorage
orsessionStorage
).
We can set storage event listeners either by using window.addEventListener("storage", func)
or by using the onstorage
attribute like so window.onstorage = func
.
Here is an example:
window.onstorage = (event) => {
if (event.key === "title"){
alert(`your new title is ${event.newValue} the previous was ${event.oldValue}`)
}
alert('SAVED!!');
}
localStorage.setItem("title", "kelly")
Before you try this, note that the function won’t be triggered on the same tab where the change occurred. The function would be triggered by other opened tabs or windows of the same domain. This feature is used to sync data on all tabs/windows of the same domain. So to test this, you might want to open another tab of the same domain.
Limitations of localStorage
There are a few limitations you should be aware of:
localStorage
can only store data up to 5 MB, so you have to ensure the data you are trying to store won’t exceed this limit. You can try executing this code in your browser console, but make sure your localStorage is empty before you test it by calling the.clear()
method.
localStorage.setItem('a', Array(1024 * 1024 * 5).join('a'))
localStorage.setItem('b', 'a')
// Uncaught DOMException: Failed to execute 'setItem' on 'Storage': Setting the value of `a` exceeded the quota.
In the example above, we get an error because we created a string that is 5 MB large, which is the max value we can store, so adding any more data would exceed that limit.
It can only store string data. A convention that has been adopted to store JavaScript objects and arrays is to serialize them into JSON strings then store them. When we want to retrieve the objects, we deserialize them and get our JavaScript object. Use
JSON.stringify()
to serialize JavaScript objects andJSON.parse()
to deserialize JSON string to a JavaScript object.Data stored in
localStorage
is not accessible to web workers.localStorage
is synchronous, so operations are executed one at a time.
Security Vulnerabilities of Local Storage
localStorage
can be exploited easily by XSS attacks. Sensitive information shouldn’t be stored in local storage.Restrict developer access to data, as there is no server-side storage. Information is stored in the browser.
When To Use Local Storage
When you know the size of data that will be stored beforehand. Ensure it doesn’t exceed 5 MB.
If you are storing data that is not sensitive.
The data you are storing is of
String
datatype or can be serialized and deserialized to strings easily.
Conclusion
In this article, we looked at what localStorage
is and the methods used to interact with data stored in localStorage
. Now that you understand its benefits and drawbacks, you can decide how and when to use it in your applications.
This content originally appeared on Telerik Blogs and was authored by Ifeoma Imoh
Ifeoma Imoh | Sciencx (2022-11-03T07:11:01+00:00) JavaScript Local Storage: All You Need To Know!. Retrieved from https://www.scien.cx/2022/11/03/javascript-local-storage-all-you-need-to-know/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.