Loading ...
Sorry, an error occurred while loading the content.

Re: && as flow control

Expand Messages
  • pauanyu
    I am not Douglas, so I cannot speak for him, but here is my opinion on the matter. I believe the reason JSLint does not accept using && and || for flow control
    Message 1 of 12 , Mar 18, 2010
    • 0 Attachment
      I am not Douglas, so I cannot speak for him, but here is my opinion on the matter.

      I believe the reason JSLint does not accept using && and || for flow control is because they are usually misunderstood and confusing to people who are not experienced with JavaScript.

      I have seen some people who assumed that those two operators return true or false, not the operands. Until you have sufficient knowledge and experience with JavaScript, using those operators for flow control can be very confusing.

      Which brings me to my second point: style. JSLint, in addition to checking for genuine errors, also occasionally enforces style conventions as well, usually with the goal of making your code more readable.

      Compare these two blocks of code:

      (typeof foo === "function") && foo();

      if (typeof foo === "function") {
      foo();
      }

      Although the first is certainly more concise, it is also confusing to people who do not understand how boolean operators work in JavaScript. On the other hand, almost everybody understands how "if" blocks work. As a consequence, the second version is less confusing, though it also consumes more space.

      Personally, I like using the boolean operators for flow control, but I believe the issues above are why JSLint forbids it.

      --- In jslint_com@yahoogroups.com, "Dave" <david.hampton@...> wrote:
      >
      > Many languages allow a convenience in scripting that allows an && to be used as flow control.
      >
      > var foo = [1,2,3,4];
      >
      > foo[0] && fop = foo.shift(); //assigns the first element of foo to fop, if it exists.
      >
      > Conversely, an || statement can be used for alternate functionality.
      >
      > JavaScript also allows this, but jslint does not. I'm curious as to why.
      >
      > Dave
      >
      > P.S., this may have been answered asked before, but it seems that the search functionality of YAHOO! Groups scrubs the '&' character...
      >
    Your message has been successfully submitted and would be delivered to recipients shortly.