Declaring Multiple Variables in JavaScript

2019-01-01 00:22发布

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

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

...or like this:

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

Is one method better/faster than the other?

16条回答
宁负流年不负卿
2楼-- · 2019-01-01 00:23

My only, yet essential use for comma is in a for loop:

for (var i = 0, n = a.length; i < n; i++) {
  var e = a[i];
  console.log(e);
}

I went here to look up whether this is OK in JavaScript.

Even seeing it work, a question remained whether n is local to the function.

This verifies, n is local:

a=[3,5,7,11];
(function l () { for (var i = 0, n = a.length; i < n; i++) {
  var e = a[i];
  console.log(e);
}}) ();
console.log(typeof n == "undefined" ?
  "as expected, n was local" : "oops, n was global");

For a moment I wasn't sure, switching between languages.

查看更多
看淡一切
3楼-- · 2019-01-01 00:25

I believe that before we started use ES6, approach with single var declaration was neither good nor bad (in case if you have linters and 'use strict'. It was really taste preference. But now things changed for me. There 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 untill you really need let. So quite often your code will contain variable declarations with assigment 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 convinient to do that with multiline declarations.

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

查看更多
栀子花@的思念
4楼-- · 2019-01-01 00:26

ECMAScript6 introducted destructuring assignment which works pretty nice:

[a, b] = [1, 2] a will equal 1 and b will equal 2.

查看更多
看淡一切
5楼-- · 2019-01-01 00:27

I think it's a matter of personal preference. I prefer to do it in the following way :

   var /* Vars */
            me = this, that = scope,
            temp, tempUri, tempUrl,
            videoId = getQueryString()["id"],
            host = location.protocol + '//' + location.host,
            baseUrl = "localhost",
            str = "Visit W3Schools",
            n = str.search(/w3schools/i),
            x = 5,
            y = 6,
            z = x + y
   /* End Vars */;
查看更多
唯独是你
6楼-- · 2019-01-01 00:29

I think the first way (multiple vars) is best, as you can otherwise end up with this (from an application that uses Knockout), which is difficult to read in my opinion:

    var categories = ko.observableArray(),
        keywordFilter = ko.observableArray(),
        omniFilter = ko.observable('').extend({ throttle: 300 }),
        filteredCategories = ko.computed(function () {
            var underlyingArray = categories();
            return ko.utils.arrayFilter(underlyingArray, function (n) {
                return n.FilteredSportCount() > 0;
            });
        }),
        favoriteSports = ko.computed(function () {
            var sports = ko.observableArray();
            ko.utils.arrayForEach(categories(), function (c) {
                ko.utils.arrayForEach(c.Sports(), function (a) {
                    if (a.IsFavorite()) {
                        sports.push(a);
                    }
                });
            });
            return sports;
        }),
        toggleFavorite = function (sport, userId) {
            var isFavorite = sport.IsFavorite();

            var url = setfavouritesurl;

            var data = {
                userId: userId,
                sportId: sport.Id(),
                isFavourite: !isFavorite
            };

            var callback = function () {
                sport.IsFavorite(!isFavorite);
            };

            jQuery.support.cors = true;
            jQuery.ajax({
                url: url,
                type: "GET",
                data: data,
                success: callback
            });
        },
        hasfavoriteSports = ko.computed(function () {
            var result = false;
            ko.utils.arrayForEach(categories(), function (c) {
                ko.utils.arrayForEach(c.Sports(), function (a) {
                    if (a.IsFavorite()) {
                        result = true;
                    }
                });
            });
            return result;
        });
查看更多
美炸的是我
7楼-- · 2019-01-01 00:30

Although both are valid, using the second discourages inexperienced developers from placing var statements all over the place and causing hoisting issues. If there is only one var per function, at the top of the function, then it is easier to debug the code as a whole. This can mean that the lines where the variables are declared are not as explicit as some may like.

I feel that trade-off is worth it, if it means weaning a developer off of dropping 'var' anywhere they feel like.

People may complain about JSLint, I do as well, but a lot of it is geared not toward fixing issues with the language, but in correcting bad habits of the coders and therefore preventing problems in the code they write. Therefore:

"In languages with block scope, it is usually recommended that variables be declared at the site of first use. But because JavaScript does not have block scope, it is wiser to declare all of a function's variables at the top of the function. It is recommended that a single var statement be used per function." - http://www.jslint.com/lint.html#scope

查看更多
登录 后发表回答