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?
You can just check if the variable has a value or not. Meaning,
If you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator. e.g.
As mentioned in one of the answers, you can be in luck if you are talking about a variable that has a global scope. As you might know, the variables that you define globally tend to get added to the windows object. You can take advantage of this fact so lets say you are accessing a variable called bleh, just use the double inverted operator (!!)
This would return a false while bleh has not been declared AND assigned a value.
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: