简体   繁体   中英

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

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.

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.

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;

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++ (eg 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM