What does a comma do in assignment statements in JavaScript?

前端 未结 4 1158
盖世英雄少女心
盖世英雄少女心 2020-12-10 14:32

I found this in a piece of code and i\'m wondering what it does? Assign b to x... but what\'s with the ,c?

var x = b, c;
相关标签:
4条回答
  • 2020-12-10 14:52

    c is undefined.

    This is equivalent:

    var x = b;
    var c;
    
    0 讨论(0)
  • 2020-12-10 14:55

    That declares two variables, x and c, and assigns value b to variable x.

    This is equivalent to the more explicit form*:

    var x = b;
    var c;
    

    JavaScript allows multiple declarations per var keyword – each new variable is separated by a comma. This is the style suggested by JSLint, which instructs developers to use a single var per function (the error message from JSLint is Combine this with the previous 'var' statement.).

    * Actually, due to hoisting it will be interpreted as var x; var c; x = b.

    0 讨论(0)
  • 2020-12-10 14:58

    It's the same as

    var x = b;
    var c; 
    

    One of those so clever it's extremely stupid additions to a language.

    0 讨论(0)
  • 2020-12-10 15:08

    That defines two local variables x and c - while setting x's value equal to the value of b.

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