Exploring localStorage : Web API
What is localStorage?
JavaScript is a versatile programming language that allows developers to create dynamic and interactive web applications. One of the key features it offers is the ability to store data locally on a user's device. This local storage mechanism is achieved through a Web API called "localStorage." In this article, we will delve into what local storage is, its advantages and disadvantages, and some common use cases.
localStorage
is a Web Storage API in JavaScript that allows web applications to store data persistently on a user's device. Unlike session storage, which only lasts for the duration of a page session, local storage data remains intact even after the browser is closed and reopened. It uses a simple key-value pair storage mechanism and can store data in the form of strings.
What is the Web storage API?
The Web Storage API is a set of web technologies that provide web developers with a way to store data locally in a user's web browser. It consists of two main storage mechanisms: localStorage
and sessionStorage
. These mechanisms allow developers to store data on the client side, which can be accessed and manipulated by JavaScript code running in the browser. Here's a brief explanation of each:
localStorage
:localStorage
provides a way to store key-value pairs of data in a persistent manner. Data stored inlocalStorage
remains available even after the user closes the browser or navigates away from the web page.Data stored in
localStorage
has no expiration date and will persist until it is explicitly removed by the web application or the user.
sessionStorage
:sessionStorage
is similar tolocalStorage
but is designed for temporary session-specific data storage.Data stored in
sessionStorage
is only available for the duration of the page session. It is automatically cleared when the user closes the browser tab or navigates away from the page.
The key features and benefits of the Web Storage API include:
Simple API: It offers a straightforward key-value storage model that is easy to use and understand.
Client-Side Storage: Data is stored on the client side (in the user's browser), reducing the need for server-side storage and reducing server load.
Fast Access: Data stored in Web Storage is easily accessible and can be quickly retrieved using JavaScript.
Security: Web Storage is subject to the same-origin policy, which means that data stored in it can only be accessed by JavaScript code from the same domain. This provides a level of security against cross-site scripting (XSS) attacks.
Storage Limitations: Web Storage has limitations on the amount of data that can be stored (usually around 5-10 MB per domain, depending on the browser).
Data Types: Data in Web Storage is typically stored as strings, but you can easily convert data types like numbers or JSON objects into strings for storage and parse them when retrieved.
Web Storage is commonly used for scenarios where you need to store user preferences, session data, or cached data in a web application. It's a convenient alternative to using server-side storage or cookies for certain types of data, and it can improve the performance and user experience of web applications.
Using localStorage
- Storing Data: You can store data in local storage using the
setItem
method. This method takes a key (a string) and a value (also a string) and stores them as a key-value pair.
localStorage.setItem("username", "JohnDoe");
localStorage.setItem("email", "johndoe@example.com");
As we’ve already noted, localStorage
can only store strings. To store arrays or objects, you would have to convert them to strings. To do this, we use the JSON.stringify()
method before passing to setItem()
, like so:
const array = ["JohnDoe",20]
localStorage.setItem('user', JSON.stringify(array));
- Retrieving Data: You can retrieve data from local storage using the
getItem
method, providing the key for the data you want to retrieve.
const username = localStorage.getItem("username");
const email = localStorage.getItem("email");
In the case of arrays and objects, you need to convert the data back to its original format using the parse()
method. Study the code below for a better understanding of the importance of the parse()
method.
const userData = localStorage.getItem("user");
// '["JohnDoe",20]'
const parsedUserData = JSON.parse(userData);
// ["JohnDoe",20]
- Removing Data: You can remove data from local storage using the
removeItem
method. This method takes the key as its parameter.
localStorage.removeItem("email");
- Clearing All Data: localStorage.clear();
localStorage.clear();
Remember that the data stored in
window.localStorage
is limited by the storage capacity of the browser, which is typically around 5-10 MB, and it is accessible to JavaScript running on the same domain.
When to use localStorage?
While localStorage
is a suitable option for storing small amounts of data, it is not recommended for managing large data sets. It's worth noting that localStorage
is accessible to any user of the device, so it should not be used to store sensitive information. However, it can be employed effectively for saving user preferences such as language or theme settings and for caching frequently used data. Another useful application of localStorage
is storing form data, ensuring it remains intact even if the user closes their browser.
Applications that involve user authentication, localStorage
can serve as a means to maintain session data, allowing users to stay logged in even after closing and reopening the browser. Essentially, localStorage
facilitates the storage and retrieval of data. In the forthcoming tutorial, we will demonstrate this through a simple to-do app. In the meantime, if you need a refresher on using localStorage
with JavaScript, you can refer to the video tutorial below.
Where the data in localStorage is stored?
The data in localStorage
is stored in the web browser on the user's device. It is a part of the Web Storage API and provides a simple key-value storage mechanism. This means that the data is stored locally on the user's computer or mobile device, specifically within the browser's storage system. It's important to note that localStorage
is domain-specific, so data stored in localStorage
for one website or web application is not accessible to other websites or applications, and it can only be accessed by JavaScript code running on the same domain.
sessionStorage vs localStorage
- sessionStorage: It is another web storage mechanism that is similar to local storage but with a key difference: data stored in session storage is only available for the duration of a page session. Once the user closes the browser tab or navigates away from the page, the data is deleted. Session storage is often used for temporary storage, such as storing data needed for a particular browsing session. To use session storage, you can access it via the
sessionStorage
object.
// Store data in session storage
sessionStorage.setItem("theme", "light");
// Retrieve data from session storage
const theme = sessionStorage.getItem("theme");
- localStorage: It is a type of web storage that allows web applications to store key-value pairs locally on a user's device. Data stored in local storage remains persistent across browser sessions and even after the browser is closed and reopened. It is often used to store user preferences, settings, and other data that should be available for the long term. To use
localStorage
, you can access it via thelocalStorage
object.
// Store data in local storage
localStorage.setItem("username", "JohnDoe");
// Retrieve data from local storage
const username = localStorage.getItem("username");
Sorting in localStorage:
localStorage
is a key-value storage mechanism, and it does not inherently support sorting data. However, you can sort the data that you store in localStorage
by following these steps:
Retrieve Data: First, you need to retrieve the data from
localStorage
. This data is typically stored as an array of objects or as a JSON string.Parse Data: If the data is stored as a JSON string, you need to parse it into a JavaScript object.
const data = JSON.parse(localStorage.getItem('yourDataKey'));
- Sort the Data: You can use JavaScript's built-in array sorting methods to sort the data. For example, you can use the
sort
method with a custom comparison function to sort an array of objects based on a specific property:
data.sort((a, b) => {
// Compare objects based on a specific property, e.g., 'name'
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
});
- Store the Sorted Data Back in LocalStorage: Once you have sorted the data, you can store it back in
localStorage
. Be sure to convert it back to a JSON string if it's an array of objects.
localStorage.setItem('yourDataKey', JSON.stringify(data));
Here's a complete example of sorting data stored in localStorage
:
// Step 1: Retrieve data from localStorage
const data = JSON.parse(localStorage.getItem('yourDataKey'));
// Step 2: Sort the data based on a specific property (e.g., 'name')
data.sort((a, b) => {
if (a.name < b.name) {
return -1;
}
if (a.name > b.name) {
return 1;
}
return 0;
});
// Step 3: Store the sorted data back in localStorage
localStorage.setItem('yourDataKey', JSON.stringify(data));
Remember to adjust the property and sorting logic to suit your specific data structure and sorting requirements. This approach allows you to sort the data you have stored in
localStorage
in a custom manner.
How to check if your browser supports localStorage:
localStorage
, as a type of web storage, is an HTML5 specification. It is supported by major browsers, including Internet Explorer v8. To be sure the browser supports localStorage
, you can check using the following snippet:
if (typeof(Storage) !== "undefined") {
// LocalStorage is supported in this browser
console.log("LocalStorage is supported in this browser.");
} else {
// LocalStorage is not supported in this browser
console.log("LocalStorage is not supported in this browser.");
}
These were the basics on the Web Storage API and more precisely on localStorage. To be able to build complicated stuff, you should be able to understand the basics of the tech you're gonna use. With DevHub, all developers have the opportunity to build a basic foundation and eventually create something beautiful and valuable!
Please join the DevHub community on Discord by clicking here.
Subscribe to my newsletter
Read articles from Pratham Shah directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by