You have to differentiate between cases:
- Variables can be
undefinedor 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 about0andfalse, usingif(obj.undefProp)is ok. There’s a common idiom based on this fact:value = obj.prop || defaultValuewhich means “ifobjhas 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 theinoperator insteadvalue = ('prop' in obj) ? obj.prop : defaultValue