5

When a button is clicked I check if something exists in a localstorage key as such:

var a = localStorage.getItem('foo');
if (typeof a != 'undefined') {
    // Function
}

but if the key doesn't exists at all, it return null. How can I call if not undefined and not null do function, else return true(?) or continue?

isNaN1247
  • 17,793
  • 12
  • 71
  • 118
jQuerybeast
  • 14,130
  • 38
  • 118
  • 196

2 Answers2

4

JavaScript has a concept of falsy values... i.e. 0, null, undefined and an empty string.

Because of this, you should be able to just check if a is "truthy" (i.e. not one of the values I've mentioned above), by doing this:

var a = localStorage.getItem('foo');
if (a) {
    // Function
}

More information from SitePoint available here

isNaN1247
  • 17,793
  • 12
  • 71
  • 118
1

You should not use JavaScript's falsy comparisons if false, 0, NaN, or the empty string are valid values in your localStorage.

Instead you should check if the item is equal to null or is equal to undefined:

var a = localStorage.getItem('foo');
if (a === null || a === undefined) {
    // Function
}

Note that the triple equals (===) operator compares exactly, without type coercion. Using double equals (==) operator a special set of rules are applied to covert similar values but of different types. One of the most useful of these is that null == undefined, allowing simplification the above code:

var a = localStorage.getItem('foo');
if (a != null) {
    // Function
}

If a is null or undefined the code inside will not run.

Community
  • 1
  • 1
jgawrych
  • 3,322
  • 1
  • 28
  • 38