Declaring multiple variables in JavaScript

后端 未结 17 983
时光说笑
时光说笑 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:36

    Besides maintainability, the first way eliminates possibility of accident global variables creation:

    (function () {
    var variable1 = "Hello, World!" // Semicolon is missed out accidentally
    var variable2 = "Testing..."; // Still a local variable
    var variable3 = 42;
    }());
    

    While the second way is less forgiving:

    (function () {
    var variable1 = "Hello, World!" // Comma is missed out accidentally
        variable2 = "Testing...", // Becomes a global variable
        variable3 = 42; // A global variable as well
    }());
    

提交回复
热议问题