Explanation of JSHint's Bad line breaking before '+' error

JavascriptJshint

Javascript Problem Overview


Can someone explain to me why JSHint complains about the following,

window.location.href = String1
    + '#'
    + Sting2
    + '='
    + String3;

With the error, Bad line breaking before '+' error

I understand that this error can be configured with the laxbreak option, which is described as >This option suppresses most of the warnings about possibly unsafe line breakings in your code. It doesn't suppress warnings about comma-first coding style. To suppress those you have to use laxcomma (see below).

This explanation is pretty terse and I am curious about why breaking lines this way is considered bad or lax in the first place.

Keep in mind I am not trying to start a holy war here, I am just looking for an objective answer about why the JSHint folks think this is bad, whether it is just a style preference they are injecting into their linter (I thought JSLint was the opinionated linter), or if there is something that can go wrong on certain interpreters when line breaking this way.

Javascript Solutions


Solution 1 - Javascript

It's a style guide to avoid statements that could be liable to assumptions about automatic semicolon insertion.

The idea is that you make it clear by the end of a line whether the expression ends there or could be continued on the next line.

Solution 2 - Javascript

Jshint wont flag this as a bad line break if you use the + before the line break as opposed to in the new line. Like so:

window.location.href = String1 +
'#' +
Sting2 +
'=' +
String3;

Solution 3 - Javascript

Not a direct answer to the question but for anyone coming across this from Googling (as I did) who wish to keep the rule but fix the warnings, the following may be useful...

When using Notepad++ (e.g. with JSLint plugin), this can be fixed using the following search & replace:

  • Find what: (\r\n|\n|\r)( *)\+
  • Replace with:  +$1$2  (including the first and last space)
  • Search Mode: Regular expression

(Only tested on Windows but the regex should also work with Unix or Mac OS line endings.)

To do a similar thing for ||, &&, ==, !=, <= or >= instead of +, use this:

  • Find what: (\r\n|\n|\r)( *)(\|\||&&|==|!=|<=|>=)
  • Replace with:  $3$1 $2  (including the first and last space)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJames McMahonView Question on Stackoverflow
Solution 1 - JavascriptBarneyView Answer on Stackoverflow
Solution 2 - JavascriptasulaimanView Answer on Stackoverflow
Solution 3 - JavascriptSteve ChambersView Answer on Stackoverflow