Saturday, 1 July 2017

jquery - How to check if a variable is both null and /or undefined 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.


Answer



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;

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...