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;
}
You can directly use the equality operator
demo @ How to determine if variable is undefined or null using JavaScript
If you prefer plain javascript try this:
Otherwise, if you are already using underscore or lodash, try:
I know this is an old question, but this is the safest check and I haven't seen it posted here exactly like that:
It will cover cases where value was never defined, and also any of these:
P.S. no need for strict equality in typeof value != 'undefined'
Although an oldie, what forget is that they should wrap their code block and then catch the error and then test...
So you really don't have to check for a potential problem before hand, you simply catch it and then deal with it how you want.
The first answer with best rating is wrong. If value is undefined it will throw an exception in modern browsers. You have to use:
or
You are a bit overdoing it. To check if a variable is not given a value, you would only need to check against undefined and null.
This is assuming
0
,""
, and objects(even empty object and array) are valid "values".