Introduction
Accidentally closing a web page while filling out a form can be infuriating. You lose all the data you filled out and have to start over. In this article, you will learn how to use localStorage in JavaScript to store your data beyond a browsing session. We will show you how to use this mechanism and the Window.localStorage property, and we will review the basics of web storage in JavaScript.
What is LocalStorage in JavaScript?
localStorage is a feature that allows sites and JavaScript applications to store key-value pairs in a web browser without an expiration date. This means that the stored data persists even after the user closes the browser or restarts the computer.
localStorage is a property of the window object that makes it a global object that can interact with and manipulate the browser window. It can also be used in combination with other window properties and methods.
What is Window.localStorage?
The localStorage mechanism is available through the Window.localStorage property. Window.localStorage is part of the Window interface in JavaScript that represents a window containing a DOM document.
The Window interface has a wide range of functions, constructors, objects, and namespaces. Window.localStorage is a read-only property that returns a reference to the local storage object used to store data that is accessible only to the resource that created it.
When to use localStorage
In simple terms, localStorage is used to store and retrieve data. While you can store small amounts of data with localStorage, it is not suitable for large data sets. localStorage is accessible to anyone using the device, so you should not use it to store sensitive information. You can use it to store user preferences such as language or theme. You can also use it to cache data if it is used frequently. localStorage can store form data that will not be lost if the user closes the browser.
If you have an application that requires you to log in, localStorage can be used to persist session data. You can still log in even after closing and reopening the browser. We will demonstrate this later in this tutorial using a simple application to do the job.
Where is localStorage stored?
In Google Chrome, web storage data is stored in an SQLite file in a subfolder in the user profile. The subfolder is located in \AppData\Local\Google\Chrome\User Data\Default\Local Storage on Windows machines and ~/Library/Application Support/Google/Chrome/Default/Local Storage on macOS. Firefox stores storage objects in an SQLite file called webappsstore.sqlite, which is also located in the user profile folder.
Introduction to Web Storage API
localStorage is one of two mechanisms in the Web Storage API, the other being sessionStorage. The Web Storage API is a set of mechanisms that enable browsers to store key-value pairs. It is designed to be much more intuitive than using cookies.
Key-value pairs represent storage objects that are similar to objects, except that they remain intact during page load and are always strings. You can access these values as if they were an object or using the getItem() method (more on that later).
sessionStorage vs. localStorage
Both sessionStorage and localStorage have a separate storage area for each resource available for the duration of the page session. The main difference between them is that sessionStorage maintains only one storage area. At the same time, the browser is open (including when the page is reloaded or refreshed) while localStorage continues to store data after the browser is closed.
localStorage stores data that does not expire, while sessionStorage only stores data for a session. It is important to note that localStorage data loaded in an incognito browsing session is cleared after the last private tab is closed. The setItem SessionStorage method is useful when temporary storage of data is required, and should be used in situations where data persistence is not required beyond the current session.
SessionStorage typically has lower storage limits compared to localStorage, often limited to a few megabytes per resource. This makes it suitable for storing temporary data during a user session without consuming too much browser resources.
LocalStorage, on the other hand, provides a larger storage capacity, often ranging from 5 to 10 MB per origin. It is suitable for storing larger amounts of data that need to persist across multiple sessions.
Advantages and disadvantages of LocalStorage
localStorage in JavaScript is an important tool for storing client-side data. However, it has several advantages and disadvantages that you should consider.
Benefits
The first advantage of LocalStorage is one we've mentioned a few times before, which is that stored data doesn't expire. You can still access the data offline, and localStorage stores data that can be used without an internet connection.
Storing data with localStorage is more secure than storing it with cookies, and you have more control over your data. Finally, localStorage has a larger storage capacity compared to cookies. While cookies can only store four kilobytes of data, LocalStorage can store up to five megabytes of data.
Disadvantages
localStorage is synchronous, meaning that each operation is executed only one after the other. This causes minimal problems for smaller data sets, but as your data grows, this can become a big problem.
Although LocalStorage is more secure than cookies, you still shouldn't use it to store sensitive data. Anyone with access to the user's device can access data stored with localStorage. Additionally, localStorage can only store strings, so if you want to store other types of data, you'll need to convert them to strings. And finally, storing too much data with localStorage can slow down your application.
How does LocalStorage work?
You've heard it many times before – localStorage stores data. And if you store data, it means you might need to retrieve it later. In this section, we'll look at exactly how localStorage works. Here's a summary of how it works:
- setItem(): adds the key and value to localStorage
- getItem(): Retrieves/gets items from localStorage
- removeItem(): Removes an item from localStorage
- clear(): Clears all data from localStorage
- key(): stores a number to retrieve the local key
Saving data with setItem()
The setItem() method allows you to store values in localStorage. It takes two parameters: a key and a value. The key can be referenced later to fetch the associated value. Here's how it should look:
localStorage.setItem('name', 'Obaseki Nosa');
In the above code you can see that name is the key and Obaseki Nosa is the value. As we mentioned earlier, localStorage can only store strings. To store arrays or objects in localStorage, you need to convert them to strings.
To do this, we use the JSON.stringify method before passing it to setItem(), like this:
const userArray = ["Obaseki",25]
localStorage.setItem('user', JSON.stringify(userArray));Retrieving information with getItem()
getItem() allows you to access data stored in the browser's localStorage object. This method accepts only one parameter, the key, and returns the value as a string:
localStorage.getItem('name');
This returns a string with the value “Obaseki Nosa”. If the specified key does not exist in localStorage, it returns null. In the case of an array, we use the JSON.parse() method, which converts the JSON string into a JavaScript object:
JSON.parse(localStorage.getItem('user'));
Using the array we created above, here's how to retrieve it from localStorage:
const userData = JSON.parse(localStorage.getItem('user'));
console.log(userData);This method returns the array [“Obaseki”, 25]. You can inspect the web page and find it in the console, like this:
This image is from Firefox, so it will look a little different in other browsers. Let's compare it to another array that is not stored with localStorage:
const userArray2 = ["Oscar", 27];
console.log(userArray2);Now, we have two arrays in the console, as shown below:
Normally, if you comment them out in your code editor, they should disappear from the console. But anything stored with localStorage will remain. Here's an example:
Removing data with removeItem()
To remove an item from localStorage, you will use the removeItem() method. When passed the key name, the removeItem() method removes the existing key from memory. If there is no item associated with the given key, this method does nothing. Here is the code:
.localStorage.removeItem('name');
How to delete everything in localStorage: clear()
To delete everything in localStorage, you use the clear() method. This method, when called, clears the entire storage space of all records for that domain. It does not take any parameters. Use the following code:
localStorage.clear();
How to get the name of a key: key()
The key() method comes in handy when you need to loop through keys but still be able to pass a number or list to localStorage to retrieve the key name. Here's what it looks like:
localStorage.key(index);The index parameter represents the zero-based index of the key whose name you want to retrieve.
localStorage vs. cookies
Both LocalStorage and cookies are used to store client-side data. As we mentioned earlier, cookies can only store a maximum of four kilobytes of data, which is significantly less than the five megabyte storage capacity of LocalStorage.
Cookies are automatically sent to the server with every HTTP request, but localStorage remains local on the user's device. This can improve web performance and does not increase network traffic because it does not share data with the server.
As we have seen, the data you store with localStorage does not expire. It remains there indefinitely unless you manually delete it. Cookies, on the other hand, can be set to expire after a period of time or as soon as the browser is closed. Cookies typically store data such as user preferences and login/authentication information. This data is accessible across all browser tabs and windows. However, localStorage only stores data that is accessible on a specific protocol or domain.
Browser localStorage support
localStorage, as a type of web storage, is an HTML5 specification. It is supported by major browsers including Internet Explorer v8. You can use the following snippet to check if the browser supports localStorage:
if (typeof(Storage) !== "undefined") {
// Code for localStorage
} else {
// No web storage Support.
}Advanced techniques for managing data in localStorage
Now, we'll explore some advanced techniques for managing data in local storage. We'll work on how to effectively delete keys, apply best practices for storing and organizing objects, and use JSON parsing and stringification for complex data.
Effective key removal
Effectively removing keys from objects stored in localStorage is essential for optimizing storage space, especially if you are building an application where data is frequently updated or deleted. Removing unnecessary keys helps prevent LocalStorage from being clustered with useless data.
To effectively remove a key from an object in localStorage, you can retrieve the object using the key, remove the desired property, and then return the updated object to localStorage. This minimizes unnecessary data manipulation and storage overhead:
// Example of efficient key removal
let storedData = JSON.parse(localStorage.getItem('key'));
delete storedData.propertyToRemove;
localStorage.setItem('key', JSON.stringify(storedData));Save and organize objects
JSON parsing and stringification are powerful techniques for managing complex data structures when storing and retrieving data in localStorage. They allow for easy conversion between JavaScript objects and JSON strings, enabling efficient data management and manipulation.
When storing complex data structures such as objects or arrays in localStorage, it is essential to stringify them using JSON.stringify() before setting them in localStorage. This converts the JavaScript object into a JSON string, which can then be stored as a key-value pair:
// Storing an object in LocalStorage
let dataObject = { key: 'value' };
localStorage.setItem('objectKey', JSON.stringify(dataObject));
// Retrieving and parsing the object from LocalStorage
let retrievedObject = JSON.parse(localStorage.getItem('objectKey'));When dealing with nested objects or arrays, ensure that all nested objects are also stringified and parsed to maintain data structure integrity:
// Storing and retrieving nested objects in LocalStorage
let nestedObject = { key1: 'value1', key2: { nestedKey: 'nestedValue' } };
localStorage.setItem('nestedObject', JSON.stringify(nestedObject));
let retrievedNestedObject = JSON.parse(localStorage.getItem('nestedObject'));Result
In this article, we explored the capabilities of LocalStorage in JavaScript as a simple and efficient way to store and retrieve data without relying on cookies. We explained how and when to use localStorage, as well as how to store, retrieve, and delete items in localStorage. We demonstrated LocalStorage in action through a working example and compared it to cookies.
In this post, you learned how and when to use localStorage. We explained how to store, retrieve, and delete items in localStorage. We also created a working application to see how LocalStorage works in a practical scenario. Finally, we compared it to cookies.
So, you've come to the right place with a great tool that's easy to use with broad browser support.












