Proper way of multiple variable assignment in Javascript

This question already has an answer here:

  • Multiple left-hand assignment with JavaScript 6 answers

  • It is not okay, since those 2 code examples are not identical. The first one equals to:

    var b1;
    b4 = 100;
    b3 = b4;
    b2 = b3;
    b1 = b2;
    

    So you only define b1 in the local scope, the b2..b4 are declared globally. Which means this MUST BE completely avoided.

    I also highly doubt console.log(b1); outputs 100 as per your example.

    (function(){
        var b1 = b2 = b3 = b4 = 100;
    })();
    
    console.log(b1); //100 <-- this is not true
    console.log(b2); //100
    console.log(b3); //100
    console.log(b4); //100
    

    From the other hand - for already declared variables - initialization or assignment using

    // we assume a, b and c have been declared already
    a = b = c = 100;
    

    is a subject of your project/team conventions. From technical perspective it's fine to use it.

    链接地址: http://www.djcxy.com/p/69974.html

    上一篇: 关于Javascript变量初始化的建议

    下一篇: Javascript中多重变量赋值的正确方法