Table of Contents
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:
JAVASCRIPTconst 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:
JAVASCRIPTif (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!
- Getting Started with Solid
- Getting Started with Express
- Getting Started with Electron
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- How to deploy a PHP app using Docker
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Using Push.js to Display Web Browser Notifications
- Getting Started with React