How to check whether a Storage item is set?

How to check whether a Storage item is set?

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);
}

Solutions/Answers:

Solution 1:

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:

Solution 2:

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.

Solution 3:

The shortest way is to use default value, if key is not in storage:

var sValue = localStorage['my.token'] || ''; /* for strings */
var iValue = localStorage['my.token'] || 0; /* for integers */

Solution 4:

You can also try this if you want to check for undefined:

if (localStorage.user === undefined) {
    localStorage.user = "username";
}

getItem is a method which returns null if value is not found.

Related:  JavaScript window.scroll vs. window.scrollTo?

Solution 5:

For TRUE

localStorage.infiniteScrollEnabled = 1;

FOR FALSE

localStorage.removeItem("infiniteScrollEnabled")

CHECK EXISTANCE

if (localStorage[""infiniteScrollEnabled""]) {
  //CODE IF ENABLED
}

Solution 6:

if(!localStorage.hash) localStorage.hash = "thinkdj";

Or

var secret =  localStorage.hash || 42;