HTML5 LocalStorage: Checking if a key exists

Gabriel picture Gabriel · Apr 15, 2013 · Viewed 235.4k times · Source

Why this does not work ?

if(typeof(localStorage.getItem("username"))=='undefined'){
    alert('no');
};

The goal is to redirect the user from the index page to the login page if not already logged. Here the localStorage.getItem("username")) variable is not defined for the moment.

It's for an ios phonegap app.

Answer

UltraInstinct picture UltraInstinct · Apr 15, 2013

Quoting from the specification:

The getItem(key) method must return the current value associated with the given key. If the given key does not exist in the list associated with the object then this method must return null.

You should actually check against null.

if (localStorage.getItem("username") === null) {
  //...
}