0 Replies Latest reply on Aug 18, 2009 11:36 PM by NSurveyor

    or vs ||, and vs &&

    NSurveyor Level 2

      Hi everyone.

       

      I just thought I would poke my head in here after making a startling realisation (which maybe everyone else was already aware of but something to which I have been blind).

       

      Anyway,

       

      While learning PHP, I noticed that

      doSomething() or die("FAIL!");
      


      is a somewhat common technique for trying something, and if it happens to fail, exit out with an error message. Of course, this seemed rather funny, though logical, as to how "or" was being used. After doing some research, I learned that in most programming languages, OR uses "short-circuit evaluation", that is, if the first expression evaluates to true, there is no reason to even evaluate the second expression. Therefore, in the above code, if doSomething() returns true, then die() will not be called. On the other hand, if doSomething() returns false, the second expression is evaluated, resulting in die(). Not only does PHP do this, but in fact most programming languages evaluate OR in this manner.

       

      But what about Flash?

       

      I never noticed it before, but the deprecated "or" operator does not employ "short-circuit evaluation". Instead, both expressions are evaluated and if either is true, the logical expression is true. On the other hand, "||" follows suit with most programming languages in that it will not evaluate the second expression if the first is already true.

       

      An analogous statement can be made for  "and"  and &&. After a false is encountered, && returns false, while "and" will evaluate both.

       

      These can be very useful for making less redundant code or exploiting it as seen in the PHP example, though at the same time, if not aware of this gem, could be rather devestating in that one expects the second expression to be evaluated when sometimes it will not.

       

      Well known or not, I find it terribly fascinating!

       

      Oh and just another random, but related, tidbit, while JavaScript and Flash may seem very similar, x || y will return x if true, or return y if true, or simply false, while Flash will return only true or false.