In JavaScript, is chained assignment okay?

前端 未结 6 1140
南笙
南笙 2020-12-01 08:59

Am not new to JS or its syntax, but sometimes, the semantics of the language has me stumped at times. At work today, a colleague mentioned this:

var a = b =          


        
6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 09:34

    Yes, they're not the same. var a = b = [] is equivalent to

    var a;
    b = [];
    a = b;
    

    Not only do both a and b get assigned the same value (a reference to the same empty array), b is not declared at all. In strict mode in ECMAScript 5 and later, this will throw a ReferenceError; otherwise, unless there is already a variable b in scope, b is silently created as a property of the global object and acts similarly to a global variable, wherever the code is, even inside a function. Which is not good.

    You can see this quite easily:

    (function() {
        var a = b = [];
    })();
    
    console.log(b); // Shows []
    

提交回复
热议问题