views:

54

answers:

1

how can i check if an item is set in js? currently i am using

if (!(localStorage.getItem("infiniteScrollEnabled") == true || localStorage.getItem("infiniteScrollEnabled") == false)) {
    // init variable/set default variable for item
    localStorage.setItem("infiniteScrollEnabled", true);
}
+3  A: 

The getItem method in the WebStorage specification, explicitly returns null is 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) {
  //...
}

Note: While the WebStorage specification by definition allows you to store any arbitrary JavaScript object as the value of an storage item, this is not implemented yet on any browser (Bug reports: Firefox, Chorium), the storage item values are type-converted to string.

This can give you problems, like in your example, if you store a Boolean value, it will be converted to string, for example:

localStorage.setItem('test', true);
localStorage.getItem('test') == true; // false!!!

That happens because we are comparing a String with a Boolean value:

"true" == true; // false
"false" == false; // false

Also, if you try to store an object, it will be also converted to String.

See this related question:

CMS
Could you add your own method to `localStorage` to encapsulate this little test? E.g. `localStorage.hasItem("infiniteScrollEnabled")`?
Paul D. Waite
@Paul: Yes, you could even augment the `Storage.prototype` object, but as a rule of thumb I always recommend to [not modify objects you don't own](http://www.nczonline.net/blog/2010/03/02/maintainable-javascript-dont-modify-objects-you-down-own/), specially host objects.
CMS
@CMS: ooh yeah, good points in there. Coming from a CSS background, the idea that I can fix browser issues myself is exciting, but I can see how mucking around with the browser’s objects could get confusing.
Paul D. Waite