Yes there is; it’s the answer below. Note I needed to exclude false
by adding a check value === false
to the code below as that was a valid value for me.
You can just check if the variable has a
truthy
value or not. That meansif( value ) { }
will evaluate to
true
ifvalue
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 theToBoolean
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.Further read: http://typeofnan.blogspot.com/2011/01/typeof-is-fast.html
Thanks to [WayBack] User jAndy – Stack Overflow who answered the above at [WayBack] Is there a standard function to check for null, undefined, or blank variables in JavaScript? – Stack Overflow.
–jeroen