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 have to differentiate between cases:
undefinedor undeclared. You’ll get an error if you access an undeclared variable in any context other thantypeof.A variable that has been declared but not initialized is
undefined.Undefined properties , like
someExistingObj.someUndefProperty. An undefined property doesn’t yield an error and simply returnsundefined, which, when converted to a boolean, evaluates tofalse. So, if you don’t care about0andfalse, usingif(obj.undefProp)is ok. There’s a common idiom based on this fact:which means “if
objhas the propertyprop, assign it tovalue, otherwise assign the default valuedefautValue“.Some people consider this behavior confusing, arguing that it leads to hard-to-find errors and recommend using the
inoperator instead