Created
June 18, 2019 05:04
-
-
Save CMCDragonkai/5ae1bec291885df936c707157ef15fe4 to your computer and use it in GitHub Desktop.
Checking Types in JavaScript #javascript
This file contains 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
// 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