jshint: Ternary line breaking

var a = (tern)
    ? b
    : c;

This code produces the warning: Bad line breaking before '?'.

The jshint flow control is:

First catch the “?” token and then pass it to the expression function

  infix("?", function(left, that) {
    increaseComplexityCount();
    that.left = left;
    that.right = expression(10);
    advance(":");
    that["else"] = expression(10);
    return that;
  }, 30);

Function expression contains this logic near it’s start

    var isDangerous =
      state.option.asi &&
      state.tokens.prev.line !== startLine(state.tokens.curr) &&
      _.contains(["]", ")"], state.tokens.prev.id) &&
      _.contains(["[", "("], state.tokens.curr.id);

    if (isDangerous)
      warning("W014", state.tokens.curr, state.tokens.curr.id);

It appears the JSHint code is incorrectly catching the line break between the “)” and the “?” in its ASI logic. ASI must not apply in this case. Breaking a ternary onto multiple lines makes the code easier to read. Example:

var a = (tern1 > 0)
        ? b
        : (tern2 > x)
            ? c
            : d,
    e = 1;

About this issue

  • Original URL
  • State: open
  • Created 9 years ago
  • Reactions: 4
  • Comments: 19 (15 by maintainers)

Most upvoted comments

why are you still using JSHint, and not only JSLint which is much better?

@prettydiff this passes jshint

/* jshint laxbreak: true */
var a = (tern)
    ? b
    : c;

So, just turn that option on to not get warnings.

laxbreak will be removed in the near future. this is the issue raised for removing it - #1867