Created
December 18, 2018 11:14
-
-
Save kfiil/07448047d2cae6e0ab2d8c213f1abe0c to your computer and use it in GitHub Desktop.
Check for null, undefined, or blank variables in 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
/** | |
Test for "value is null or undefined" is | |
**/ | |
if ( some_variable == null ){ | |
// some_variable is either null or undefined | |
} | |
// So these two lines are equivalent: | |
if ( typeof(some_variable) !== "undefined" && some_variable !== null ) {} | |
if ( some_variable != null ) {} |
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
/** | |
Test for truthy value, https://stackoverflow.com/a/5515349 | |
**/ | |
// You can just check if the variable has a truthy value or not. That means | |
if( some_variable ) { | |
// some_variable is some_variable | |
} | |
// will evaluate to true if value is not: | |
// null | |
// undefined | |
// NaN | |
// empty string ("") | |
// 0 | |
// false | |
// The above list represents all possible falsy values in ECMA-/Javascript. Find it in the specification at the ToBoolean section, http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment