How to Check if a Key exists in Local Storage using JavaScript
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!
- How to Install Node on Windows, macOS and Linux
- How to Serve Static Files with Nginx and Docker
- How to deploy a PHP app using Docker
- Getting Started with Deno
- Getting Started with Sass
- Learn how to use v-model with a custom Vue component
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with Vuex: Managing State in Vue