63

What is the best practice for line continuation in JavaScript? I know that you can use \ for strings. But how would you split the following code?

var statement = con.createStatement("select * from t where
(t.a1 = 0 and t.a2 >=-1)
order by a3 desc limit 1");
0

4 Answers 4

84

If I properly understood your question:

var statement = con.createStatement('select * from t where '
                                  + '(t.a1 = 0 and t.a2 >=-1) '
                                  + 'order by a3 desc limit 1');

For readability, it is fine to align + operator on each row. Otherwise you can enclose your string in backticks and break the statement as you prefer, e.g.

var statement = con.createStatement(`
   select * from t where 
   (t.a1 = 0 and t.a2 >=-1) 
   order by a3 desc limit 1
`);
13
  • 1
    I made a stupid error here. It's easy to forget to write a space between strings. Be aware of the space between the strings (you have it correct), if space is missing the SQL statement won't work.
    – xralf
    Commented May 9, 2012 at 12:46
  • 2
    Could you explain why \ is not standard javascript? Like, is it never mentioned in the ecmascript spec, frowned upon or otherwise not 'standard' ?
    – Michahell
    Commented Nov 14, 2014 at 22:59
  • 3
    By the way, "select * " is a bad practice, especially when generating the query from a dynamic SQL string. This can become a security nightmare, among other things. It is a much better practice to explicitly indicate the columns and use a database procedure call or table-valued function call to ensure that you reduce the liability of SQL-injection. In SQL Server, dynamic SQL should always use sp_executesql.
    – devinbost
    Commented Nov 30, 2014 at 14:27
  • 1
    yes, A whitespace after that character could generate a parsing error
    – Dan D.
    Commented Mar 17, 2017 at 3:32
  • 1
    @devinbost there is nothing bad practice here, he is using static parameters in his query. Semantically, he wants all columns from t where a1 equals zero and a2 is greater than -1. The number of columns to be returned has nothing to do with sql injection.
    – cowbert
    Commented Aug 28, 2017 at 17:06
27

I like using backslashes for JavaScript line continuation, like so:

    // validation
    $(".adjustment, .info input, .includesAndTiming input, \
        .independentAdj, .generalAdj, .executiveAdj \
        #officeExpense, #longDistanceExpense, #digitalImages, #milesReimbursment, #driveTime, #statementTranscription").keypress(function (event) {
2
  • 1
    The issue with using backslashes is that a minification tool applied after the fact may cause the code to stop working. Commented Apr 22, 2015 at 22:23
  • 6
    Do you have any examples to support this? Running through jscompress.com seems to work fine. Commented Apr 23, 2015 at 12:49
9

My personal preference is similar to your first response there, but for my eyes its readability is easier:

var statement = con.createStatement
   (
   'select * from t where ' +
   '(t.a1 = 0 and t.a2 >=-1) ' +
   'order by a3 desc limit 1'
   );

It strikes a close similarity to the SQL syntax format I've been using for nearly 20 years:

SELECT *
FROM t
WHERE 
   t.a1 = 0 AND
   t.a2 >=-1
ORDER BY a3 DESC
LIMIT 1

Keeping the continuation (+ in JavaScript or AND in SQL) on the far right permits the eye to slide evenly down the left edge, checking lvalues & syntax. That's slightly more difficult to do with the continuation on the left - not important unless you do a LOT of this stuff, at which point every calorie you spend is a calorie that might've been saved by a slight improvement in format.

Since this query is so simple, breaking it all out to SQL format is wasteful of space and bandwidth, which is why the suggested JavaScript is on six lines instead of ten. Collapsing the curlies up one line each brings it to four lines, saving whitespace. Not quite as clear or as simple to edit, though.

1

The "+" is for concatenation of strings and most of the examples are dealing with strings. What if you have a command you need to string across multiple lines, such as a compound "if" statement? You need a backslash at the end of each line that is to be continued. This escapes the invisible next line character so that it will not delimit the command in mid statement.

4
  • No, you don't need continuations to continue an expression or statement. Only a string or regex can need it.
    – doug65536
    Commented May 18, 2016 at 6:27
  • 1
    @doug65536 There are exceptions though due to automatic semicolon insertion. For instance, if you put return on one line and the expression you'd like to return on a subsequent line, the function will just return undefined because it ran return;. Gotta love Javascript... Commented Jul 24, 2019 at 23:38
  • @MarredCheese Yes, that is correct. In the end one has to understand ASI to work around whitespace being significant in some contexts. One can restrict their formatting style and mostly not have to worry about it, though. My doing that so much makes me forget how easily ASI can unexpectedly change the meaning of the code.
    – doug65536
    Commented Jul 25, 2019 at 0:24
  • 1
    If you have code that goes over multiple lines I would strongly urge wrapping it in parens (i.e. ( ... )) which avoids ASI issues in a far more readable form and does not involve the range of risks that use of `` brings to your code.
    – jwpfox
    Commented Sep 21, 2020 at 9:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.