As you have noted correctly, the variable declaration expressions will be evaluated from left to right. The left hand side of the assignment will be evaluated first, right hand side of the assignment expression will be evaluated next, and then assigned.
In the second case, you got NaN
, because of variable hoisting. When JavaScript sees
bar = foo + 1,
it will know that foo
is defined in the current context, but not yet assigned a value. So, by default, it uses undefined
for foo
.
console.log(undefined + 1);
# NaN
That is why NaN
is assigned to bar
.
According to the ECMA 5.1 Standard Docs' Variable Statement
section, variable declaration will be evaluated like this
VariableStatement:
var VariableDeclarationList ;
VariableDeclarationList :
VariableDeclaration
VariableDeclarationList , VariableDeclaration*
Here, the production will be evaluated like this
The production VariableDeclarationList : VariableDeclarationList , VariableDeclaration is evaluated as follows:
- Evaluate VariableDeclarationList.
- Evaluate VariableDeclaration.
So, the left most assignment expressions should be evaluated first, and at the last only, the right most one. So, the behavior you see, is the expected behavior.