Value returned by the assignment
Why does the regular assignment statement (say, x = 5
) return the value assigned (5
in this case), while the assignment combined with a variable declaration (var x = 5
) returns undefined
?
I got the return values by executing these statements in the Chrome browser's Javascript console:
> var x = 5;
undefined
> y = 5;
5
That's the way the language was designed. It is consistent with most languages.
Having a variable declaration return anything other than undefined
is meaningless, because you can't ever use the var
keyword in an expression context.
Having assignment be an expression
not a statement
is useful when you want to set many variable to the same value at once:
x = y = z = 2;
It can also be used like this:
x = 2*(y = z); // Set y = z, and x = 2*z
However that is not the most readable code and it would probably be better written as:
y = z;
x = 2*z;
That's because var x = 5;
is a variable statement, not an expression.
The behaviour of this statement is described in Section 12.2 of the ECMAScript Language Reference.
- Evaluate VariableDeclarationList.
- Return (normal, empty, empty).
This is basically a void
return value.
The assignment operator (i.e., the equals sign) (1) assigns the right-side-operand (i.e., a value or the value of a variable, property, or function) to the left-side-operand (i.e., variable or property) and then (2) the assignment expression (e.g., y = 10) becomes a simple operand with the same value as its right-side-operand (e.g., 10) before the rest of the expression is evaluated. This is similar to when a called function is replaced with its return value when an expression is evaluated (although function calls are first in the order of operations and assignment operations are fourteenth):
var x, y, z = 1;
x = z + (y = 2); // x === 3
function returnTwo () {
return 2;
}
x = z + returnTwo(); // x === 3
Take note that not only does x now equal 3, but the entire expression evaluates to 3.
The purpose of the var
keyword is to bind variables to the current scope. Variables declared with the var
keyword are bound to the scope where they are declared. The var
keyword assigns the left-most variable (or property) as a reference to the value of the evaluated expression:
var fun = function () {
var x = 1;
var y = x + 1;
return y;
}
// The x and y variables are bound to the scope of the fun function.
Using the var
keyword with an expression is called a declaration. Declarations are actions that do not evaluate to a value, not even undefined (even though your console is printing undefined). Further, declarations cannot appear where JavaScript expects an expression, as other answers to this post have shown.
When you write var x = 5;
it declares x
and initalizes its value to 5.
This is a VariableStatement
, it returns nothing,
but x=5
is an expression
that assigns 5 to x.
as there is no x
, JavaScript implicitly creates a global x
in normal code