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.
To check if a key exists in HTML local storage by using JavaScript, you can use the getItem() method of the localStorage object.
You can store the value in localStorage with the key value pair. It has two methods setItem(key, value) to store the value in the storage object and getItem(key) to retrieve the value from the storage object. document. getElementById("result").
Quoting from the specification:
The getItem(key) method must return the current value associated with the given key. If the given key does not exist in the list associated with the object then this method must return null.
You should actually check against null
.
if (localStorage.getItem("username") === null) {
//...
}
This method worked for me:
if ("username" in localStorage) {
alert('yes');
} else {
alert('no');
}
Update:
if (localStorage.hasOwnProperty("username")) {
//
}
Another way, relevant when value is not expected to be empty string, null or any other falsy value:
if (localStorage["username"]) {
//
}
The MDN documentation shows how the getItem
method is implementated:
Object.defineProperty(oStorage, "getItem", {
value: function (sKey) { return sKey ? this[sKey] : null; },
writable: false,
configurable: false,
enumerable: false
});
If the value isn't set, it returns null
. You are testing to see if it is undefined
. Check to see if it is null
instead.
if(localStorage.getItem("username") === null){
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With