Line continuation characters in JavaScript

前端 未结 4 447
情话喂你
情话喂你 2021-02-03 17:21

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?

4条回答
  •  礼貌的吻别
    2021-02-03 17:43

    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.

提交回复
热议问题