Search code examples
javascriptcontrol-flowshort-circuiting

Are there examples of short-circuit control flow in Javascript?


http://en.wikipedia.org/wiki/Short-circuit_evaluation says "Short-circuit operators are, in effect, control structures" and http://en.wikipedia.org/wiki/Perl_language_structure#Control_structures says "Short-circuit logical operators are commonly used to affect control flow at the expression level", with a pseudo code example directly from the latter being:

expr && expr

I've seen the above sort of thing recommended in the book Minimal Perl. So why not in Javascript? Yesterday I wrote something such as the following:

myModule && myModule.myMethod(); //instead of if (myModule) myModule.myMethod();

Does anybody know of any other examples of usage of this idiom in Javascript, perhaps from open source frameworks? What might be it's disadvantages, if any (besides, "somebody might not understand it")?


Solution

  • In React conditional rendering can be achieved inline with the logical && operator, see https://reactjs.org/docs/conditional-rendering.html#inline-if-with-logical--operator Here's the pertinent snippet (my inline observations are not meant critically, checking length is the smallest and most understandable for a sample):

      return (
        // Don't directly check length, instead 
        // consider a more flexible "shouldRender" method
        <div>
          <h1>Hello!</h1>
          {unreadMessages.length > 0 &&
            <h2>
              You have {unreadMessages.length} unread messages.
            </h2>
          }
        </div>
      );