Possible Duplicate:
Detecting an undefined object property in JavaScript
How to determine if variable is 'undefined' or 'null'
Is there a standard function to check for null, undefined, or blank variables in JavaScript?
In my code, I have a condition that looks like
if (variable !== null && variable !== undefined) {
}
But instead of doing it in two steps, i.e checking if it is not defined and not null. Is there a one step checking that replaces this check.
A variable cannot be both
nullandundefinedat the same time. However, the direct answer to your question is:One
=, not two.There are two special clauses in the "abstract equality comparison algorithm" in the JavaScript spec devoted to the case of one operand being
nulland the other beingundefined, and the result istruefor==andfalsefor!=. Thus if the value of the variable isundefined, it’s not!= null, and if it’s not null, it’s obviously not!= null.Now, the case of an identifier not being defined at all, either as a
varorlet, as a function parameter, or as a property of the global context is different. A reference to such an identifier is treated as an error at runtime. You could attempt a reference and catch the error:I would personally consider that a questionable practice however. For global symbols that may or may not be there based on the presence or absence of some other library, or some similar situation, you can test for a
windowproperty (in browser JavaScript):or