Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to split long JavaScript if conditions into multiple lines?

Tags:

javascript

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.

like image 311
Aniket Suryavanshi Avatar asked Mar 19 '15 20:03

Aniket Suryavanshi


People also ask

Is it possible to break JavaScript code into multiple lines?

There are two ways to break JavaScript code into several lines: We can use the newline escape character i.e “\n”. if we are working on the js file or not rendering the code to the html page. We can use the <br> tag.

How do you break up a long if statement?

Long if statements may be split onto several lines when the character/line limit would be exceeded. The conditions have to be positioned onto the following line, and indented 4 characters. The logical operators ( && , || , etc.)

Can IF statement have 3 conditions JavaScript?

Using either “&&” or “||” i.e. logical AND or logical OR operator or combination of can achieve 3 conditions in if statement JavaScript.


1 Answers

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.

like image 106
Oriol Avatar answered Sep 18 '22 15:09

Oriol