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

Updated onbyAlan Morel
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:

JAVASCRIPT
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:

JAVASCRIPT
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!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.