News for hackers. Stuff that matters.
Re:Why 1 && 2 == 2 by lotharbot on Friday July 19, 2013 @12:03AM (#6068263)
Once you understand short-circuit evaluation, it opens up certain coding tricks.

The line "[operation] or [error condition]" will attempt the operation on the left. If it succeeds, the program continues on the next line, ignoring the part about the error condition. If it fails, the error condition will execute instead. This might be something like "open file or die".

Likewise, "[operation] and [success condition]" will attempt the operation on the left, and if it succeeds, perform the operation on the right. This might be something like "read input and process it", which will perform the (possibly expensive) processing step only when input is received.

Code written in this style is sometimes, but not always, faster to execute. It's also sometimes, but not always, clearer.

See also http://en.wikipedia.org/wiki/Short-circuit_evaluation

Re:Why 1 && 2 == 2 by cldr on Friday July 19, 2013 @12:06AM (#6068272)
This is commonly seen in Perl and PHP with stuff like

    launchMissiles() or die('failure');
Re:Why 1 && 2 == 2 by pyre on Friday July 19, 2013 @01:27AM (#6068472)
It's worth noting that in Perl the 'or' and 'and' operators are not equivalent to || and &&. For instance, they have super low operator precedence:

  my $variable = 0 or 1;
Would result in $variable == 0 because it really looks like this:

  (my $variable = 0) or 1;
I allowed myself to get burned by this once because I didn't read the fine print. ^^;;
Re:Why 1 && 2 == 2 by k3n on Friday July 19, 2013 @12:58AM (#6068406)
Ugh, `or` is mostly useless in PHP.

That code is identical to:

    launchMissiles() || die('failure');
Re:Why 1 && 2 == 2 by ars on Friday July 19, 2013 @06:18AM (#6069247)
That code is the same, but or has a lower priority than ||, so they are not the same is the code before the or is an expression.

Also, using or instead or || for these types of things is more readable since it makes your intent of conditional code execution (as opposed to boolean evaluation) clear.

Re:Why 1 && 2 == 2 by k3n on Friday July 19, 2013 @11:23AM (#6070739)
Meh, it's not more unreadable unless you have issues understanding || in the first place... and "or" is still a boolean operation.

Considering 99.9% of it's use in PHP is some variant of "connect() or die()", I stand by my statement. Besides, those "connect() or die()" expressions are widely considered bad-practice in the first place.

Re:Why 1 && 2 == 2 by eridius on Friday July 19, 2013 @01:01AM (#6068416)
The better form of this would be

    launchMissiles() and die('mutual annihilation");
Re:Why 1 && 2 == 2 by k3n on Friday July 19, 2013 @12:52AM (#6068397)
For fun, sometimes I'll rewrite JS trying not to use any explicit conditionals (keywords if/else/), and use short-circuiting instead. It's a fun exercise but I know better than to commit the code, I think I'd be dead several times over by now...