Reputation: 204
I have a series of if and else if statements and what I want is to determine a scenario in terms of local storage being empty.
I've tried:
(if localStorage.getItem('example') == localStorage.clear()) {
//Do something if that local storage item is empty
}
I am aware the program may think I'm assigning the local storage to clear out it's contents. So would I do something like:
(if localStorage.getItem('example') == localStorage()) {
//Do something if that local storage item is empty
}
If not, how can I refer to the local storage as an empty object so the program doesn't get confused thinking that I'd like to clear the contents in the storage?
Upvotes: 0
Views: 158
Reputation: 677
Ok both answers posted are right. However, I want to explain a few things that I have experienced. Undefined is returned if you are referring to the object as so and it has nothing in it:
localStorage.key; //will be undefined if not set
localStorage.getItem() returns null if nothing is in it (as I have experienced).
localStorage.getItem('key'); //will return null if not set
And yes, all you have to do is check if it is null or undefined (depending on the method you use)
if(localStorage.getItem('key') === null){
//do stuff here
}
or
if(localStorage.key === undefined){
//do stuff here
}
or you can use the ! operator like so:
if(!localStorage.getItem('key')){
//do stuff here
}
or
if(!localStorage.key){
//do stuff here
}
The reason for this is because both null and undefined are falsely values, and the ! operator checks for falsely values
Upvotes: 1
Reputation: 15867
You can check to see if it is null.
if(localStorage.getItem('example') === null){
console.log("x");
}
Upvotes: 2
Reputation: 866
You can just check if localStorage.getItem()
is undefined
. Here's an example:
function isCleared(item) {
return !localStorage.getItem(item)
}
Upvotes: 0