How to check whether a Storage item is set?

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:

  • Storing Objects in HTML5 localStorage

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.


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 */