How can I check if an item is set in localStorage? Currently I am using
if (!(localStorage.getItem("infiniteScrollEnabled") == true || localStorage.getItem("infiniteScrollEnabled") == false)) { // init variable/set default variable for item localStorage.setItem("infiniteScrollEnabled", true); }
The getItem method in the WebStorage specification, explicitly returns null if the item does not exist:
... If the given key does not exist in the list associated with the object then this method must return null. ...
So, you can:
if (localStorage.getItem("infiniteScrollEnabled") === null) { //... } See this related question:
You can use hasOwnProperty method to check this
> localStorage.setItem('foo', 123) undefined > localStorage.hasOwnProperty('foo') true > localStorage.hasOwnProperty('bar') false Works in current versions of Chrome(Mac), Firefox(Mac) and Safari.
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