javascript tutorial - [Solved-5 Solutions] Standard function to check for null - javascript - java script - javascript array
Problem:
Is there a universal JavaScript function that checks that a variable has a value and ensures that it's not undefined or null ?
function isEmpty(val){
return (val === undefined || val == null || val.length <= 0) ? true : false;
}
click below button to copy the code. By JavaScript tutorial team
Solution 1:
We can just check if the variable has a truthy value or not. That means
if( value ) {
}
click below button to copy the code. By JavaScript tutorial team
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. Furthermore, if we do not know whether a variable exists (that means, if it was declared) we should check with the typeof operator. For instance
if( typeof foo !== 'undefined' ) {
// foo could get resolved and it's defined
}
click below button to copy the code. By JavaScript tutorial team
If we can be sure that a variable is declared at least, we should directly check if it has a truthyvalue like shown above.
Solution 2:
// value is undefined or null
return value === undefined || value === null;
JavaScript ninjas could use the == operator:
return value == null;
click below button to copy the code. By JavaScript tutorial team
Solution 3:
function isEmpty(value){
return (value == null || value.length === 0);
}
click below button to copy the code. By JavaScript tutorial team
This will return true for
undefined // Because undefined == null
null
[]
""
click below button to copy the code. By JavaScript tutorial team
and zero argument functions since a function's length
is the number of declared parameters it takes.
To disallow the latter category, we might want to just check for blank strings
function isEmpty(value){
return (value == null || value === '');
}
click below button to copy the code. By JavaScript tutorial team
Solution 4:
The first answer with best rating is wrong. If value is undefined it will throw an exception in modern browsers. We have to use:
if (typeof(value) !== "undefined" && value)
or
if (typeof value !== "undefined" && value)
click below button to copy the code. By JavaScript tutorial team
Solution 5:
We know this is an old question, but this is the safest check and we haven't seen it posted here exactly like that:
if (typeof value != 'undefined' && value) {
//deal with value'
};
click below button to copy the code. By JavaScript tutorial team
It will cover cases where value was never defined, and also any of these:
- null
- undefined (value of undefined is not the same as a parameter that was never defined)
- 0
- "" (empty string)
- false
- NaN
P.S. no need for strict equality in typeof value != 'undefined'