Javascript How to define multiple variables on a single line?

后端 未结 7 2022
渐次进展
渐次进展 2020-11-28 22:20

Reading documentation online, I\'m getting confused how to properly define multiple JavaScript variables on a single line.

If I want to condense the following code,

7条回答
  •  再見小時候
    2020-11-28 22:59

    You want to rely on commas because if you rely on the multiple assignment construct, you'll shoot yourself in the foot at one point or another.

    An example would be:

    >>> var a = b = c = [];
    >>> c.push(1)
    [1]
    >>> a
    [1]
    

    They all refer to the same object in memory, they are not "unique" since anytime you make a reference to an object ( array, object literal, function ) it's passed by reference and not value. So if you change just one of those variables, and wanted them to act individually you will not get what you want because they are not individual objects.

    There is also a downside in multiple assignment, in that the secondary variables become globals, and you don't want to leak into the global namespace.

    (function() {  var a = global = 5 })();
    alert(window.global) // 5
    

    It's best to just use commas and preferably with lots of whitespace so it's readable:

    var a = 5
      , b = 2
      , c = 3
      , d = {}
      , e = [];
    

提交回复
热议问题