Declaring multiple variables in JavaScript

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

    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

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

    The first way is easier to maintain. Each declaration is a single statement on a single line, so you can easily add, remove, and reorder the declarations.

    With the second way, it is annoying to remove the first or last declaration because they start from the var keyword and finish with the semicolon respectively. Every time you add a new declaration, you have to replace the semicolon in the last old line with a comma.

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

    It's just a matter of personal preference. There is no difference between these two ways, other than a few bytes saved with the second form if you strip out the white space.

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

    My only, yet essential, use for a 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.

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

    I think the first way (multiple variables) is best, as you can otherwise end up with this (from an application that uses KnockoutJS), 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;
            });
    
    0 讨论(0)
提交回复
热议问题