Chaining assignments in var declarations

suggest change

In a non-strict classic script, chaining assignments in a var declaration creates a global binding unintentionally. In strict mode and in modules, the assignment to the undeclared name throws a ReferenceError instead.

For example:

(function foo() {    
    var a = b = 0;
})()
console.log('b: ' + b); // "b: 0" in non-strict code
console.log('a: ' + a); // ReferenceError: a is not defined

The first log prints b: 0. The second throws ReferenceError because a is local to the function. b became global. Assignment is right-to-left, so the declaration is evaluated as

var a = (b = 0);

The correct way to chain var assignments is:

var a, b;
a = b = 0;

Or:

var a = 0, b = a;

This will make sure that both a and b will be local variables.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents