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.