Proper JavaScript line breaking?

时间:2016-02-03 03:10:45

标签: javascript

Is breaking up a long boolean expression like this

var x = a === b && c === d && e === f;

To something more readable like

var x = a === b
        && c === d
        && e === f;

considered bad practice? With long variable names the former can become extremely long.

2 个答案:

答案 0 :(得分:2)

You are free to put line breaks in an expression like this. It is not considered a bad practice. In fact, it's a good practice to keep your code readable without lots of horizontal scrolling so if some line breaks are required in order to do that, then it is recommended.

Many corporate coding style guides specify a max code line length for easy reading and line breaks like this are required in order to follow those types of guidelines.

Check out Douglas Crockford's javascript conventions or even Google's Style Guide with a select quote from each:

Google JavaScript Style Guide

When possible, all function arguments should be listed on the same line. If doing so would exceed the 80-column limit, the arguments must be line-wrapped in a readable way. To save space, you may wrap as close to 80 as possible, or put each argument on its own line to enhance readability. The indentation may be either four spaces, or aligned to the parenthesis.

Crockford's Code Conventions for the JavaScript Programming Language

Avoid excessively long lines. When a statement will not fit nicely on a single line, it may be necessary to break it. It is best to break after a { left brace, [ left bracket, ( left paren, , comma, or before a . period, ? question mark, or : colon. If such a break is not feasible, then break after an operator and continue on the next line with 8 spaces added to the current indentation. Those 8 spaces do not change the current indentation.

MDN Coding Style

Line length

80 characters or less (for laptop side-by-side diffing and two-window tiling

答案 1 :(得分:1)

Write a function in this case to make it short and clean. It is because that we should hide the details and only write the code with same abstract layer in one function (suggested in the book "Clean Code").

So,

var x = computeX();
...
function computeX() {
  var logic1 = (a === b);
  var logic2 = (c === d);
  var logic3 = (e === f);
  return logic1 && logic2 && logic3;
}

Make sure you also give them good names.