by ender7 · 14y ago · 0 comments
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)The issue is abusing && or || as the whole of an expression statement, instead of using if.
var foo = obj && obj.bar; // great
!isActive && $parent.toggleClass('open'); // smelly
if (!isActive) $parent.toggleClass('open'); // better if (!isActive) {
$parent.toggleClass('open');
} // best
Damian Conway of Perl fame wrote an excellent style guide for C in the early/mid 90s which I'm pretty sure explained why (I can't find my copy):Programmer A:
if (!isActive) $parent.toggleClass('open');
Programmer B: if (!isActive)
$parent.toggleClass('open');
doSomethingElse();
Oh dear. // okay
if (!isActive) $parent.toggleClass('open');
// not okay
if (!isActive)
$parent.toggleClass('open');
That way you know when you change it to two lines, you have to add curlies.https://github.com/h5bp/html5-boilerplate/blob/master/index....
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.