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;
}
Best Solution
You can just check if the variable has a
truthyvalue or not. That meanswill evaluate to
trueifvalueis not:The above list represents all possible
falsyvalues in ECMA-/Javascript. Find it in the specification at theToBooleansection.Furthermore, if you do not know whether a variable exists (that means, if it was declared) you should check with the
typeofoperator. For instanceIf you can be sure that a variable is declared at least, you should directly check if it has a
truthyvalue like shown above.