Is it me, or did the author tack on a new topic regarding the use of && and ||?
The fact that they return the controlling operand is quite useful. Consider a situation where you want to check the property of an object, but don't know if that object is null:
var foo = obj && obj.bar;
I find this much more readable than:
var foo = null;
if (obj) {
foo = obj.bar;
}
You can accomplish the same thing with a ternary operator, but it's longer and, to my eyes, less scannable:
var foo = obj ? obj.bar : null;
Also useful when setting optional parameters:
function myFunc(foo, bar) {
foo = foo || {};
bar = bar || 'default_value';
}
(take care however: the empty string evaluates to false, as does [] and 0)
Your last parenthetical point is exactly why I'd avoid those uses of && and ||. Write a default_to() function (or a method in languages that allow methods to be defined on the null object) that wraps all those corner cases up.
Your post has made me realize however that I'm not sure if the language I'm reimplementing is meant to be value preserving in the case of those operators where an explicit corrosion from the a type to Boolean has been defined. Shows how often they're used like that in production code I guess.
The fact that they return the controlling operand is quite useful. Consider a situation where you want to check the property of an object, but don't know if that object is null:
I find this much more readable than: You can accomplish the same thing with a ternary operator, but it's longer and, to my eyes, less scannable: Also useful when setting optional parameters: (take care however: the empty string evaluates to false, as does [] and 0)