Line continuation characters in JavaScript

前端 未结 4 455
情话喂你
情话喂你 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:31

    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.

    0 讨论(0)
  • 2021-02-03 17:37

    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) {
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-03 17:47

    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
    0 讨论(0)
提交回复
热议问题