Last active
December 10, 2015 00:49
-
-
Save nathansmith/4354237 to your computer and use it in GitHub Desktop.
Utility function for checking if something exists.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Check existence | |
function exists(thing) { | |
return (!isNaN(thing) && typeof thing !== 'undefined' && thing !== null) ? thing : undefined; | |
} | |
// Or, more tersely | |
function exists(thing) { | |
// != checks `null` and `undefined` | |
return thing != null ? thing : undefined; | |
} | |
/* | |
Usage... | |
var options = { | |
latitude: 0, | |
longitude: 1 | |
}; | |
var lat = exists(options.latitude); | |
var lon = exists(options.longitude); | |
*/ |
thing != null
simply will check both the null
and undefined
cases, but no other cases. I think preferable to checking both cases explicitly like this.
@getify Good call. Forgot about that.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
After being bitten by loose existence checking…
And having it bomb out on values that are
0
(falsey), I've started using this littleexists
function to handle variable assignment where a valid value can be zero.