43
if ( true && true ||
  false && false ||
  true && true ) {
  console.log( 'Splitting condition into multiple lines worked!' );
}

Does the above snippet of code work in all relevant browsers?

PS: I'm also concerned about IE8 as it has too big a marketshare to ignore as of today.

Aniket Suryavanshi
  • 1,534
  • 3
  • 14
  • 23

3 Answers3

29

Browsers are very forgiving when it comes to whitespace and line breaks in conditionals. You can honestly get away with a lot of things (for better or worse haha). Right now these two formats are the industry standard. Personally, I like the syntax in the second syntax more.

Syntax A

if (
  a === 123 &&
  b === 'abc'
) { ... }

Syntax B

if (
  a === 123
  && b === 'abc'
) { ... }

AirBnb's preferred syntax: https://github.com/airbnb/javascript/issues/1380

Joseph Cho
  • 4,033
  • 4
  • 26
  • 33
22

This is explained in the spec:

7.3 Line Terminators

Like white space characters, line terminator characters are used to improve source text readability and to separate tokens (indivisible lexical units) from each other. However, unlike white space characters, line terminators have some influence over the behaviour of the syntactic grammar. In general, line terminators may occur between any two tokens, but there are a few places where they are forbidden by the syntactic grammar. Line terminators also affect the process of automatic semicolon insertion (7.9).

7.9 Automatic Semicolon Insertion

Certain ECMAScript statements (empty statement, variable statement, expression statement, do-while statement, continue statement, break statement, return statement, and throw statement) must be terminated with semicolons. Such semicolons may always appear explicitly in the source text. For convenience, however, such semicolons may be omitted from the source text in certain situations. These situations are described by saying that semicolons are automatically inserted into the source code token stream in those situations.

So in most cases you can do it. And your case is one of these.

Oriol
  • 274,082
  • 63
  • 437
  • 513
3

I also recently found myself having a very long condition. Below you will find an example of how I solved it, using Boolean():

const a = new Array('', '  ', '    ');
const empty = Boolean(a[0].trim() == '' || 
                      a[1].trim() == '' || 
                      a[2].trim() == '' ||);
if (!empty){
   console.log("Fine!");
}else{
   console.log("Not fine!");   
}

I hope I can help you.

Memmo
  • 298
  • 3
  • 8
  • 31