Skip to content

Instantly share code, notes, and snippets.

@CMCDragonkai
Created June 18, 2019 05:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CMCDragonkai/5ae1bec291885df936c707157ef15fe4 to your computer and use it in GitHub Desktop.
Save CMCDragonkai/5ae1bec291885df936c707157ef15fe4 to your computer and use it in GitHub Desktop.
Checking Types in JavaScript #javascript
// you often want to check if a value is truthy
function booleanise(v) {
return !!v;
}
booleanise(0) // false
booleanise('') // false (empty strings is falsey)
booleanise(false) // false
booleanise(null) // false
booleanise(undefined) // false
boolanise([]) // true (empty arrays are truthy!)
// sometimes you want to check if a value is null or undefined only
function nully (v) {
return v == null;
}
nully(null) // true
nully(undefined) // true
nully(false) // false
// so you can use if (v != null) { ... } to prevent nully values
// to check if a value is other primitive types use typeof
// for arrays use Array.isArray
// for normal objects use `value && typeof value === 'object' && value.constructor === Object`
// for classes use instanceof
// for functions use typeof
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment