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.