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!
What does the term web storage API refer to
How is localStorage different from sessionStorage and cookies
What is the definition of localStorage in JavaScript?
Understanding Window.localStorage
How does localStorage operate?
Browser support in localStorage
Best Practices for using localStorage in Javascript
Limitations of working with localStorage in Javascript
The Web Storage API is a collection of tools that allows web browsers to save data as key-value pairs. Unlike using cookies, this storage method is more user-friendly and simple to work with.
In this method, the key-value pairs represent storage objects that are comparable to objects, except that they remain unchanged even when the page reloads, and they are always stored as strings. You can retrieve these values either by accessing them like objects or by using the getItem() method, which we will discuss in detail later on.
The web storage API provides two separate tools, namely sessionStorage and localStorage. Each mechanism keeps a distinct storage area for every available origin for as long as the page session remains active.
The primary distinction between sessionStorage and localStorage is that sessionStorage only retains the storage area as long as the browser remains open, including when the page is refreshed or restored. On the other hand, localStorage continues to store data even after the browser is closed. This means that any data saved in sessionStorage is erased when the page is closed, while data saved in localStorage persists even after the browser is closed.
Cookies are another way of storing data on the client side. However, they are less secure and have a smaller storage capacity than web storage. Cookies are also sent with every HTTP request, which can affect the performance of the application.
Now. let’s focus on using localStorage in JavaScript.
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.
When working with localStorage, it's important to keep in mind the storage limit and clear local storage when necessary to prevent any potential issues. clear() method in localStorage API takes care of this.
Here, clear() deletes all the key-value pairs from localStorage, making sure the storage limit never exceeds.
For example, suppose you have a web app that lets the user choose the background color of the app and saves their choice in localStorage with the key backgroundColor.
If the user wants to reset their preferences and start fresh, you can use the clear() method to erase all the data in localStorage, including the backgroundColor key-value pair.
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.
Almost all major browsers, including Chrome, Firefox, Safari, Opera, and Edge support localStorage. However, it's important to note that the amount of storage available and the behavior of localStorage can vary slightly from browser to browser.
For example, some browsers can store more data in localStorage than others. It's always a good practice to test your web applications across multiple browsers to ensure that they work properly on all platforms.
Additionally, some older browsers may not support localStorage, so it's important to have fallback options in place for these users.
Here's an example of how you can use this code snippet to check for localStorage support in JavaScript:
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.