Search code examples
jquerynulllocal-storageundefined

Call a function only if a value is neither null nor undefined


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?


Solution

  • 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