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 ?
Solution 1:
We can just check if the variable has a truthy value or not. That means
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 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:
Solution 3:
This will return true for
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
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:
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:
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'