How to Check if a Key exists in Local Storage using JavaScript

On the browser, local storage is a useful way to store data on the user's computer.
It differs from cookies in that cookies are usually sent with each request, while local storage is stored on the user's computer and is available for use by the front-end web app.
Before you interact with the data, you will want to know if it exists or not.
In this post, we'll learn how to check if a key exists in local storage using JavaScript.
How to check if a key exists in local storage
The best way to check if a key exists in local storage is to use the getItem
method.
This method will return you the value of the key you are looking for.
If the key exists in storage, you will get back the value that resides there, otherwise you will get null
.
Let's see this in action:
const key = "my-key";
const value = localStorage.getItem(key);
const exists = value !== null;
if (exists) {
console.log("The key exists in local storage.");
} else {
console.log("The key does not exist in local storage.");
}
You can shorten this code by doing it all in one line, if you prefer:
if (localStorage.getItem("my-key") !== null) {
console.log("The key exists in local storage.");
} else {
console.log("The key does not exist in local storage.");
}
Either way, you will get back a boolean value which you can use to determine if the key exists or not.
Conclusion
In this post, we learned how to check if a key exists in local storage using JavaScript.
Simply use the getItem
method to get the value at that key, and if the value is not null
, then the key exists.
Thanks for reading!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!