How to check if the localStorage key exists or not in JavaScript
In this tutorial, we are going to learn about checking a key exists or not in localStorage using JavaScript.
Using the localStorage.getItem() method
To check if a key exists or not in localStorage, we can use the localStorage.getItem()
method.
The localStorage.getItem()
method takes the key
as an argument and returns the key’s value. if a key doesn’t exist it returns the null
.
Here is an example:
const name = localStorage.getItem('name');
if(name){
console.log('Name exists');
}else{
console.log('Name is not found');
}
In the above example, if a name
key exists in the localStorage it prints the if
block statement
or it prints the else
block statement if a key doesn’t exist.