Take Javascript debugging to the next level, with Zipy!
Get Started for free
See how thousands of Engineering, Product and Marketing Teams are accelerating their growth with Zipy.
Imagine being able to create personalized dashboards that remember a user's layout preferences, or crafting dynamic web games where players can pick up right where they left off, even if they close their browser. With web storages, this dream becomes reality.
localStorage, sessionStorage, and cookies are different types of client-side storage methods, through which you can store, retrieve, and delete data.
We are covering localStorage in this blog because it is one of the most commonly used web storage methods. Throughout this guide, we'll navigate the ins and outs of local storage and learn how to store and retrieve data effortlessly, manage complex data structures.
Let’s get started!
A set of technologies called the Web Storage API enables web browsers to store data in key-value pairs. This storage option is easier to use and more intuitive than using cookies.Using this method, key-value pairs represent objects that are similar to storage objects, with the exception that they are always stored as strings and remain intact even after a page reload. These values can be obtained by using the getItem() method, which we will go over in more depth later, or by accessing them like objects.
SessionStorage and localStorage are two distinct utilities offered by the web storage API. Every mechanism maintains a unique storage space for every available origin for the duration of the ongoing page session.
The main difference between localStorage and sessionStorage is that the formerStorage merely keeps the storage space open in the browser, even when the page is restored or refreshed. However, even if the browser is closed, data is still stored in localStorage. This implies that information saved in localStorage survives long after the browser is closed, whereas information saved in sessionStorage is deleted when the page is closed.
Another method for client-side data storage is through cookies. They do not have as much storage as web storage, though, and are less secure. Every HTTP request also includes cookies, which may have an impact on the application's performance.
Let's now concentrate on using JavaScript's localStorage.
localStorage is a JavaScript property that enables websites and applications to store key-value pairs in a web browser, which persists even after the browser window is closed. The data stays there when the user comes back or refreshes the page.
The data stored using web storage in Google Chrome is saved in an SQLite file that is stored in a subfolder of the user's profile. Here’s the code based upon the different types of machines and browsers.
In JavaScript, the localStorage mechanism can be accessed using the Window.localStorage property, which is a part of the Window interface. The Window interface is associated with a window that contains a DOM document and includes various functions, constructors, objects, and namespaces.
Window.localStorage is a read-only property that provides a reference to the local storage object. This object is used to store data, which is only accessible to the origin that created it. Therefore, any website or application can only access data that it has stored in its own origin's localStorage, and not that of any other website or application.
localStorage provides five methods that can be used in web applications to manipulate data:
Using these methods you can interact with the localStorage object and save and get data in an organized way. With these methods, web applications can persist data across page loads and even after the user closes the browser.
The setItem() method is used to add key-value pairs to the localStorage object. It needs a key and a value, and saves the value with the key. If a key already exists, the value is updated. Here's an example:
In the first line, we are storing the string "john_doe" under the key "username" in localStorage. In the second line, we are updating the value of the "username" key to "jane_doe".
Note that localStorage can only store strings, so if you want to store a non-string value, you need to convert it to a string first using JSON.stringify(). For example:
In this example, we save a thing called “user” in localStorage by making it a string with JSON.stringify(). To retrieve the object later, we would use the getItem() method and then parse the JSON string using JSON.parse().
localStorage is a web API that allows web applications to store key-value pairs in the user's web browser. One of the methods provided by the localStorage API is getItem(), which is used to retrieve the value associated with a given key.
To use getItem(), you just give the key to the method. For example, if you previously stored a value associated with the key "username", you can retrieve it with the following code:
getItem() gives null when the key is missing in the localStorage. So, check the value before using it:
getItem() can be useful for persisting data between page loads or for storing user preferences.
However, it's important to note that localStorage has a size limit of about 5-10 MB depending on the browser, and storing too much data can slow down the application. Therefore, it's recommended to use localStorage for small amounts of data.
removeItem(), which is used to remove a key-value pair from localStorage using a specified key. To use removeItem(), you simply pass the key as an argument to the method. For example, if you want to remove the value associated with the key "username" from localStorage, you can use the following code:
If the specified key is not found in localStorage, removeItem() will do nothing and the storage will remain unchanged. Therefore, it's a good practice to check if the key exists before attempting to remove it:
removeItem() can be useful for deleting sensitive data or cleaning up localStorage when it's no longer needed. It's important to note removeItem() deletes one key-value pair only. To delete all the data from localStorage, use clear(). More on clear() in the next sub-section.
To avoid any potential problems, it's crucial to remember the storage limit when using localStorage and to remove local storage when needed. This is handled via the localStorage API's clear() method.
Here, clear() ensures that the storage limit is never exceeded by deleting every key-value combination from localStorage.Consider a web application where the user can select the background colour and have it saved in localStorage using the key backgroundColor.
You can use the clear() function to remove all of the data in localStorage, including the backgroundColor key-value combination, if the user wishes to start again with their preferences.
Another scenario where you may want to clear local storage is when you're developing a web application and need to test how it behaves with an empty storage. Here, you can use clear() to delete all the data in localStorage and start fresh.
It is important to note that clearing local storage with clear() will delete all the data stored in localStorage permanently and cannot be undone. Therefore, it's recommended to use clear() with caution and provide a confirmation dialogue to the user before clearing the storage.
Additionally, it's recommended to test the behaviour of your application after clearing local storage to ensure that it handles the situation correctly.
The key() method is a useful feature of the localStorage object that allows you to retrieve the name of a key located at a specific index in localStorage. The syntax for using key() is simple and involves passing an index as an argument to the method. For example, this code gets the name of the second key in localStorage:
In this example, key(1) retrieves the name of the second key in localStorage and assigns it to the secondKey variable. The console.log() statement then outputs the name of this key to the console.
Using the key() method can be especially helpful when you need to access a specific key in localStorage and you don't know its name. By iterating through the keys in localStorage and using key() to retrieve their names, you can easily find the key you need.
LocalStorage is supported by almost all popular browsers, including Chrome, Firefox, Safari, Opera, and Edge. It is crucial to remember that the amount of storage that is accessible and the functionality of localStorage may differ slightly across different browsers.
For instance, different browsers have different capacities for localStorage data storage. To make sure your web apps function properly on all platforms, it's a good idea to test them in a variety of browsers.Additionally, fallback choices should be available for users of older browsers, as some may not support localStorage.
Here's an illustration of how to use this JavaScript code snippet to see if localStorage is supported:
This code checks if the browser supports web storage by checking if the Storage object is defined. If it is, it means the browser supports web storage, and we can use localStorage to store and retrieve data.
In this example, we set a key-value pair using localStorage.setItem(), and retrieve it using localStorage.getItem(). If web storage is not supported, the code inside the else block will execute and output a message to the console.
By keeping these limitations in mind, we can effectively and safely use localStorage in our web applications.
In this blog, we have learned how to use localStorage in JavaScript to store data on the user’s browser. We now know that localStorage is a useful feature which can be used for various purposes, such as saving user preferences, caching data, or implementing offline functionality.
There are also other types of storage in JavaScript that you can use for different scenarios. sessionStorage is similar to localStorage, but it only stores data for one session. Cookies are small pieces of data that are sent from the server to the browser and stored on the user’s device. We would highly recommend you to learn more about types of storages in JavaScript, such as localStorage, sessionStorage and cookies for better usability. Till then.
Happy Coding!
Feel free to comment or write to us in case you have any further questions at support@zipy.ai. We would be happy to help you. In case you want to explore for your app, you can sign up or book a demo.
Zipy provides you with full customer visibility without multiple back and forths between Customers, Customer Support and your Engineering teams.