You can just check if the variable have a truthy
value or not. That means
if( value ) {}
Would evaluate to true
if are not value
:
- Null
- Undefined
- NaN
- Empty string ("")
- 0
- False
The above list represents all possible falsy
values in Ecma-/javascript. Find it in the Specificationat ToBoolean
.
Furthermore, if you don't know whether a variable exists (that means, if it is declared) you should CH Eck with the typeof
operator. For instance
if( typeof foo !== ‘undefined‘ ) { // foo could get resolved and it‘s defined}
If you can being sure that a variable are declared at least and you should directly check if it have a truthy
value like sh Own above.
Further read:http://typeofnan.blogspot.com/2011/01/typeof-is-fast.html
http://stackoverflow.com/questions/5515310/ is-there-a-standard-function-to-check-for-null-undefined-or-blank-variables-in/5515349#5515349
Is there a standard function to check for null, undefined, or blank variables in JavaScript?