[javascript] How to check if a variable is both null and /or undefined in JavaScript

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.

This question is related to javascript jquery

The answer is


A variable cannot be both null and undefined at the same time. However, the direct answer to your question is:

if (variable != null)

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 null and the other being undefined, and the result is true for == and false for !=. Thus if the value of the variable is undefined, 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 var or let, 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:

var isDefined = false;
try {
  (variable);
  isDefined = true;
}
catch (x) {}

I would personally consider that a questionable practice however. For global symbols that may or may be there based on the presence or absence of some other library, or some similar situation, you can test for a window property (in browser JavaScript):

var isJqueryAvailable = window.jQuery != null;

or

var isJqueryAvailable = "jQuery" in window;

You can wrap it in your own function:

function isNullAndUndef(variable) {

    return (variable !== null && variable !== undefined);
}