Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); } 
like image 938
Jiew Meng Avatar asked Jul 16 '10 07:07

Jiew Meng


2 Answers

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
like image 161
Christian C. Salvadó Avatar answered Oct 23 '22 20:10

Christian C. Salvadó


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.

like image 23
Stephan Hoyer Avatar answered Oct 23 '22 19:10

Stephan Hoyer