We are frequently using the following code pattern in our JavaScript code
if (typeof(some_variable) != 'undefined' && some_variable != null)
{
// Do something with some_variable
}
Is there a less verbose way of checking that has the same effect?
According to some forums and literature saying simply the following should have the same effect.
if (some_variable)
{
// Do something with some_variable
}
Unfortunately, Firebug evaluates such a statement as error on runtime when some_variable
is undefined, whereas the first one is just fine for it. Is this only an (unwanted) behavior of Firebug or is there really some difference between those two ways?
In newer JavaScript standards like ES5 and ES6 you can just say
all return false, which is similar to Python's check of empty variables. So if you want to write conditional logic around a variable, just say
here "null" or "empty string" or "undefined" will be handled efficiently.
Since there is no single complete and correct answer, I will try to summarize:
In general, the expression:
cannot be simplified, because the
variable
might be undeclared so omitting thetypeof(variable) != "undefined"
would result in ReferenceError. But, you can simplify the expression according to the context:If the
variable
is global, you can simplify to:If it is local, you can probably avoid situations when this variable is undeclared, and also simplify to:
If it is object property, you don't have to worry about ReferenceError:
Checking null with normal equality will also return true for undefined.
if (window.variable == null) alert('variable is null or undefined');
whatever yyy is undefined or null, it will return true
yes
no
Testing nullity (
if (value == null)
) or non-nullity (if (value != null)
) is less verbose than testing the definition status of a variable.Moreover, testing
if (value)
(orif( obj.property)
) to ensure the existence of your variable (or object property) fails if it is defined with a booleanfalse
value. Caveat emptor :)Firstly you have to be very clear about what you test. JavaScript has all sorts of implicit conversions to trip you up, and two different types of equality comparator:
==
and===
.A function,
test(val)
that tests fornull
orundefined
should have the following characteristics:Let's see which of the ideas here actually pass our test.
These work:
These do not work:
I created a jsperf entry to compare the correctness and performance of these approaches. Results are inconclusive for the time being as there haven't been enough runs across different browsers/platforms. Please take a minute to run the test on your computer!
At present, it seems that the simple
val == null
test gives the best performance. It's also pretty much the shortest. The test may be negated toval != null
if you want the complement.