61

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");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
xralf
  • 3,312
  • 45
  • 129
  • 200

4 Answers4

79

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: Anyway, unless you're using Ecmascript 2015, avoid to split a multiline string with \, because:

  1. It's not standard JavaScript
  2. A whitespace after that character could generate a parsing error
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
  • 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 May 09 '12 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 Nov 14 '14 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 Nov 30 '14 at 14:27
  • 1
    yes, A whitespace after that character could generate a parsing error – Dee Mar 17 '17 at 03: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 Aug 28 '17 at 17:06
  • @cowbert Reason 1: https://stackoverflow.com/questions/3639861/why-is-select-considered-harmful – devinbost Aug 29 '17 at 17:47
  • @cowbert Reason 2: https://sqlblog.org/2011/09/17/bad-habits-to-kick-using-exec-instead-of-sp_executesql – devinbost Aug 29 '17 at 17:48
  • @cowbert Reason 3, part 1: https://www.mssqltips.com/sqlservertip/3637/protecting-yourself-from-sql-injection-in-sql-server--part-1/ – devinbost Aug 29 '17 at 17:50
  • @cowbert Reason 3, part 2: https://www.mssqltips.com/sqlservertip/3638/protecting-yourself-from-sql-injection-in-sql-server--part-2/ – devinbost Aug 29 '17 at 17:51
  • @devinbost: There's no security in javascript. Period. Syntax can't change that. – Poul Bak Mar 08 '20 at 05:15
  • 1
    @PoulBak If it's running in the client browser, then you're right. If it's running in the backend via node.js, that's a totally different matter. – devinbost Mar 19 '20 at 22:02
  • I always put the space at the START of the continuation string to make it more obvious that it's there and it's deliberate `s = 'string1' + ' string2' + ' string3'` – kbro May 01 '20 at 17:07
  • FWIW The Google Style Guide might be of interest in this context - https://google.github.io/styleguide/jsguide.html#features-strings-no-line-continuations – jwpfox Sep 21 '20 at 09:13
26

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) {
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user1477388
  • 20,790
  • 32
  • 144
  • 264
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
TDHofstetter
  • 268
  • 2
  • 7
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.

ThomasJ
  • 69
  • 1
  • 1
  • 6
  • No, you don't need continuations to continue an expression or statement. Only a string or regex can need it. – doug65536 May 18 '16 at 06: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... – MarredCheese Jul 24 '19 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 Jul 25 '19 at 00: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 Sep 21 '20 at 09:25