3 ms·
Replacing "if" constructions with boolean operators is powerful. The simplistic example in the article doesn't really show the purpose of using || and && to co
by jlongster 16y ago
Replacing "if" constructions with boolean operators is powerful. The simplistic example in the article doesn't really show the purpose of using || and && to control flow.
It's scalable. What if you have to test a third expression? Surely this:
foo() && bar() && buzz()
is more readable than
if(foo()) if(bar()) buzz()
It's flexible. Since an "if" statement is not an expression in most languages, you have to be careful where you place it. For example, what if you wanted to pass the result to a function?
qux(foo() && bar() && buzz());
Javascript (and a few other languages) have the neat feature with boolean operators that they return the result of the last tested expression. So the above example would pass the result of buzz() to qux if all statements are true, otherwise it would pass false. Here is the same code with "if" statements:
var res = false;
if(foo())
if(bar())
res = buzz();
qux(res);
There are many more examples of why you should be used to constructing expressions with boolean operators. It doesn't matter much for the simplistic example in the article, but the same technique allows you do write more complex code in succinct ways.
- psyklic 16y agoThis does not respond to the issue raised in the article. In all of jlongster's examples, the result of the '&&' operator is being used. So, someone reading the code can mentally consider the '&&'s to be logical operators. However, in the article's examples, the result was not being used at all. So, the '&&' was being used not as a 'logical operator' but as a 'conditional operator', which is a non-intuitive use. Also, '&&' and '||' are not Boolean operators -- they are logical operators, where order matters for short-circuiting.
- teej 16y agoFor what it's worth, I've often seen code like jlongster's example, but never seen code like the OP's example.
- aaronblohowiak 16y agousing && as a conditional operator is a common rubyism
- silvestrov 16y agoIn the first 2 examples the result of the && operator isn't used.
- aaronblohowiak 16y agomy personal favorite is: function f(p1, p2, p3){ p2 || ( p2 = "default); } and i have a buddy that likes to do "poor man's unless": if(something && other_thing || third_thing); else{ } which helps you from having to figure out the logical inversion or have the ! to track down, but is a little weird