Because assignment is an expression which evaluates to the assigned value. So this operation:
b = 1
not only assigns the value of 1
to b
but also the entire expression evaluates to the value of 1
. Since it's an expression which evaluates to a value, it can be used in place any time a value is needed.
This needs a value:
var a = (something)
So you can use any expression, for example:
var a = (b = 1)
And the parentheses are unnecessary since the assignment to a
won't occur until the expression is evaluated and a value produced:
var a = b = 1
What wouldn't work is to both declare and assign as an expression. For example:
var a = (var b = 1)
Because the declaration is not an expression, it's a statement. Statements can be thought of as "a line of code" and can't be dropped in-place in the middle of other code.
You can test this in your browser's debugging tools by entering code directly onto the console. If you do this:
var a = 1
The console will print undefined
, because the statement produced no value (even though it did assign a value to a
). If you do this:
b = 1
The console will print 1
because the expression produced a value (as well as assigned a value to b
).
Regarding the rest of the code being tested in the question, the key difference between a
and b
is that a
is declared and thus has a specific scope, whereas b
is not declared and thus defaults to a property on the window
object which is accessible anywhere.