I have noticed that Google's Closer Compiler may pack statements with variables into a preceding var
declaration producing repeated identifiers in that declaration. This is an example of the output I got:
var a = Ak - Aj,
b = Bk - Bj,
c = Math.sqrt(a*a+b*b),
a = a / c,
b = b / c
Notice how a
and b
are re-declared and assigned new values within the same var
declaration. Additionally, it looks like the old values of a
and b
are used in their second initialization. Does this produce a well defined behavior in ES5 / ES6?
The EcmaScript specification has this in the section on var
:
A
var
statement declares variables that are scoped to the running execution context's VariableEnvironment. Var variables are created when their containing Lexical Environment is instantiated and are initialized to undefined when created. Within the scope of any VariableEnvironment a common BindingIdentifier may appear in more than one VariableDeclaration but those declarations collectively define only one variable. A variable defined by a VariableDeclaration with an Initializer is assigned the value of its Initializer's AssignmentExpression when the VariableDeclaration is executed, not when the variable is created.
In other words, a variable may occur more than once in a var
statement, but the concerned variable will still only be declared once, and that declaration will happen before any code (in that scope) is executed (a.k.a. "hoisting"). The initialisations will be executed in their normal execution order.
So, by specification, your example code is equivalent to:
var a, b, c;
a = Ak - Aj;
b = Bk - Bj;
c = Math.sqrt(a*a+b*b);
a = a / c;
b = b / c;