Is there a standard function to check for null, undefined, or blank variables in JavaScript?
You can just check if the variable has a truthy
value or not. That means
if( value ) {
}
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.
Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof
operator. For instance
if( typeof foo !== 'undefined' ) {
// foo could get resolved and it's defined
}
If you can be sure that a variable is declared at least, you should directly check if it has a truthy
value like shown above.
Further read: http://typeofnan.blogspot.com/2011/01/typeof-is-fast.html
The verbose method to check if value is undefined or null is:
return value === undefined || value === null;
You can also use the ==
operator but this expects one to know all the rules:
return value == null; // also returns true if value is undefined
function isEmpty(value){
return (value == null || value.length === 0);
}
This will return true for
undefined // Because undefined == null
null
[]
""
and zero argument functions since a function's length
is the number of declared parameters it takes.
To disallow the latter category, you might want to just check for blank strings
function isEmpty(value){
return (value == null || value === '');
}