What is the difference between a single comma-separated variable declaration, and multiple declarations?

后端 未结 2 1140
清酒与你
清酒与你 2021-01-22 05:17

What is the difference between comma separated declaration:

var a=0, b=0, c=0;

and multiple line declaration:

var a=0;
var b=0;         


        
相关标签:
2条回答
  • 2021-01-22 06:14

    The comma separated declaration is just a short hand. Executing-wise there's no difference. But it can help reduce the size of your javascript file if you are declaring a lot of variables.

    You can even do:

    var a = 1, b = 'string', c = new Date();
    
    0 讨论(0)
  • 2021-01-22 06:19

    Usually famous linting styles doesn't allow, for e.g. airbnb standard, so I would say it is not really a big deal and since it is not, I'd say it is better to stick to the warnings of the others.

    Why not using comma declarations?

    So you don't have to worry about issues when a ; is mistakenly used instead of ,, which would result in a variable becoming global instead of scoped.

    var t2 = 20;
    
    const foo = function(){
      var t1 = 2; // assume that you by mistake did this
          t2 = 2;
    }
    
    foo();
    console.log(t2);
    

    Note that a small mistake like that would result in the t2 having a different value when printed, the issue is JS doesn't care if it makes no since, it assumes that you knew what you are doing and it'll change the global variable from 20 to 2.

    WARNING global variables are evil don't use them, this is just an example

    also different let, const, and var, need to be grouped together, which isn't a big deal but again since JS is amazing at failing silently you have to be careful.

    the only benefit that I see so far for using chain declarations is that you would reduce the size of the JS file over the wire, and with the modern internet speed that is not a big plus.

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