The next code is interpreted in Google-chrome console:
a = 123
123
% Ok!
var b = 123
undefined
% `undefined`? why? b is not undefined, it contains `12
var
is a statement. Statements have no value, so eval()
(which the console calls) returns undefined
.
a = 123
is a simple expression, which returns 123
(so that you can write b = a = 123
). When passed an expression, eval()
returns the expression's value.
I take it you're doing this in a console that shows you the result of the operation.
The result of an assignment expression is the value that was assigned. But var
statements don't have a result, not least because they don't occur within the usual step-by-step flow of code. We can see this in the definition of the var
statement in the spec: §13.3.2.4 tells us that the result of var
is the abstract specification call NormalCompletion(empty)
, which is just an alias for Completion{[[type]]: normal, [[value]]: argument, [[target]]:empty}
which is for indicating how a statement/expression completed. In this case, it completes with no value. (Which isn't true of all JavaScript statements, surprisingly.)