You have to differentiate between cases:
- Variables can be
undefined
or undeclared. You’ll get an error if you access an undeclared variable in any context other thantypeof
.
if(typeof someUndeclaredVar == whatever) // works if(someUndeclaredVar) // throws error
A variable that has been declared but not initialized is undefined
.
let foo; if (foo) //evaluates to false because foo === 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 about0
andfalse
, usingif(obj.undefProp)
is ok. There’s a common idiom based on this fact:value = obj.prop || defaultValue
which means “ifobj
has 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 thein
operator insteadvalue = ('prop' in obj) ? obj.prop : defaultValue