patternjavascriptCritical
Is there a standard function to check for null, undefined, or blank variables in JavaScript?
Viewed 0 times
variablesfunctioncheckstandardforundefinedblankjavascripttherenull
Problem
Is there a universal JavaScript function that checks that a variable has a value and ensures that it's not
undefined or null? I've got this code, but I'm not sure if it covers all cases:function isEmpty(val){
return (val === undefined || val == null || val.length <= 0) ? true : false;
}Solution
You can just check if the variable has a
will evaluate to
The above list represents all possible
Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the
If you can be sure that a variable is declared at least, you should directly check if it has a
truthy value or not. That meansif (value) {
// do something..
}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 instanceif (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.Code Snippets
if (value) {
// do something..
}if (typeof foo !== 'undefined') {
// foo could get resolved and it's defined
}Context
Stack Overflow Q#5515310, score: 5790
Revisions (0)
No revisions yet.