Page 196 - JavaScript
P. 196
'T'
'F'
Example 2
F() && T(); // false
Output:
'F'
Example 3
T() || F(); // true
Output:
'T'
Example 4
F() || T(); // true
Output:
'F'
'T'
Short-circuiting to prevent errors
var obj; // object has value of undefined
if(obj.property){ }// TypeError: Cannot read property 'property' of undefined
if(obj.property && obj !== undefined){}// Line A TypeError: Cannot read property 'property' of
undefined
Line A: if you reverse the order the first conditional statement will prevent the error on the second
by not executing it if it would throw the error
if(obj !== undefined && obj.property){}; // no error thrown
But should only be used if you expect undefined
if(typeof obj === "object" && obj.property){}; // safe option but slower
Short-circuiting to provide a default value
The || operator can be used to select either a "truthy" value, or the default value.
https://riptutorial.com/ 153

