Skip to content

Instantly share code, notes, and snippets.

@kfiil
Created December 18, 2018 11:14
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 kfiil/07448047d2cae6e0ab2d8c213f1abe0c to your computer and use it in GitHub Desktop.
Save kfiil/07448047d2cae6e0ab2d8c213f1abe0c to your computer and use it in GitHub Desktop.
Check for null, undefined, or blank variables in JavaScript
/**
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 ) {}
/**
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