Coder Perfect

Checking if a key exists [duplicate] in HTML5 LocalStorage

Problem

Why isn’t this working?

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

If the user is not already logged in, the purpose is to redirect them from the index page to the login page. For the time being, the localStorage.getItem(“username”) variable is undefined.

It’s for a phonegap app for iOS.

Asked by Gabriel

Solution #1

The following is a quote from the specification:

Actually, you should check for null.

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

Answered by UltraInstinct

Solution #2

For me, this way worked:

if ("username" in localStorage) {
    alert('yes');
} else {
    alert('no');
}

Answered by user3332298

Solution #3

Update:

if (localStorage.hasOwnProperty("username")) {
    //
}

Another way, relevant when value is not expected to be empty string, null or any other falsy value:

if (localStorage["username"]) {
    //
}

Answered by Derin

Solution #4

The getItem method is implemented as follows, according to the MDN documentation:

Object.defineProperty(oStorage, "getItem", {
      value: function (sKey) { return sKey ? this[sKey] : null; },
      writable: false,
      configurable: false,
      enumerable: false
    });

It returns null if the value isn’t set. You’re determining if it’s undefined. Instead, look to see if it’s null.

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

Answered by Quentin

Post is based on https://stackoverflow.com/questions/16010827/html5-localstorage-checking-if-a-key-exists