Skip to content

Instantly share code, notes, and snippets.

@nathansmith
Last active December 10, 2015 00:49
Show Gist options
  • Save nathansmith/4354237 to your computer and use it in GitHub Desktop.
Save nathansmith/4354237 to your computer and use it in GitHub Desktop.
Utility function for checking if something exists.
// 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);
*/
@nathansmith
Copy link
Author

After being bitten by loose existence checking…

var foo = o.bar || undefined;

And having it bomb out on values that are 0 (falsey), I've started using this little exists function to handle variable assignment where a valid value can be zero.

@getify
Copy link

getify commented Dec 21, 2012

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.

@nathansmith
Copy link
Author

@getify Good call. Forgot about that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment