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?
Best Answer
I think the most efficient way to test for "value is
null
orundefined
" isSo these two lines are equivalent:
Note 1
As mentioned in the question, the short variant requires that
some_variable
has been declared, otherwise a ReferenceError will be thrown. However in many use cases you can assume that this is safe:check for optional arguments:
check for properties on an existing object
On the other hand
typeof
can deal with undeclared global variables (simply returnsundefined
). Yet these cases should be reduced to a minimum for good reasons, as Alsciende explained.Note 2
This - even shorter - variant is not equivalent:
so
Note 3
In general it is recommended to use
===
instead of==
. The proposed solution is an exception to this rule. The JSHint syntax checker even provides theeqnull
option for this reason.From the jQuery style guide:
EDIT 2021-03:
Nowadays most browsers support the Nullish coalescing operator (
??
) and the Logical nullish assignment(??=)
, which allows a more concise way to assign a default value if a variable is null or undefined, for example:can be written as any of these forms