Declaring multiple variables in JavaScript

后端 未结 17 771
时光说笑
时光说笑 2020-11-22 13:16

In JavaScript, it is possible to declare multiple variables like this:

var variable1 = "Hello, World!";
var variable2 = "Testing...";
var          


        
相关标签:
17条回答
  • 2020-11-22 13:16

    I believe that before we started using ES6, an approach with a single var declaration was neither good nor bad (in case if you have linters and 'use strict'. It was really a taste preference. But now things changed for me. These are my thoughts in favour of multiline declaration:

    1. Now we have two new kinds of variables, and var became obsolete. It is good practice to use const everywhere until you really need let. So quite often your code will contain variable declarations with assignment in the middle of the code, and because of block scoping you quite often will move variables between blocks in case of small changes. I think that it is more convenient to do that with multiline declarations.

    2. ES6 syntax became more diverse, we got destructors, template strings, arrow functions and optional assignments. When you heavily use all those features with single variable declarations, it hurts readability.

    0 讨论(0)
  • 2020-11-22 13:18
    var variable1 = "Hello, World!";
    var variable2 = "Testing...";
    var variable3 = 42;
    

    is more readable than:

    var variable1 = "Hello, World!",
        variable2 = "Testing...",
        variable3 = 42;
    

    But they do the same thing.

    0 讨论(0)
  • 2020-11-22 13:19

    It's common to use one var statement per scope for organization. The way all "scopes" follow a similar pattern making the code more readable. Additionally, the engine "hoists" them all to the top anyway. So keeping your declarations together mimics what will actually happen more closely.

    0 讨论(0)
  • 2020-11-22 13:21

    Maybe like this

    var variable1 = "Hello, World!"
    , variable2 = 2
    , variable3 = "How are you doing?"
    , variable4 = 42;
    

    Except when changing the first or last variable, it is easy to maintain and read.

    0 讨论(0)
  • 2020-11-22 13:21

    Use the ES6 destructuring assignment: It will unpack values from arrays, or properties from objects, into distinct variables.

    let [variable1 , variable2, variable3] =
    ["Hello, World!", "Testing...", 42];
    
    console.log(variable1); // Hello, World!
    console.log(variable2); // Testing...
    console.log(variable3); // 42

    0 讨论(0)
  • 2020-11-22 13:21

    Another reason to avoid the single statement version (single var) is debugging. If an exception is thrown in any of the assignment lines the stack trace shows only the one line.

    If you had 10 variables defined with the comma syntax you have no way to directly know which one was the culprit.

    The individual statement version does not suffer from this ambiguity.

    0 讨论(0)
提交回复
热议问题