Coder Perfect

Checking if a key exists [duplicate] in HTML5 LocalStorage


Why isn’t this working?


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) {
} else {

Answered by user3332298

Solution #3


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