Reputation: 24502
When instantiating two variables in the same instruction:
var foo = 1,
bar = foo + 1;
in V8, this yields foo == 1
and bar == 2
,
var bar = foo + 1,
foo = 1;
and this yields foo == 1
and bar == NaN
.
Is the order of executed operations guaranteed? Or is it safer to declare foo
and bar
separately?
var foo = 1;
var bar = foo + 1;
or even
var foo, bar;
foo = 1;
bar = foo + 1;
Upvotes: 1
Views: 80
Reputation: 239473
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.
Upvotes: 3
Reputation: 90
When declaring and initializing variables in the same instruction, javascript executes the actions in exactly the order you would expect.
For example,
var foo = 1,
bar = foo + 1;
is perfectly valid, and will never produce errors. On the other hand
var bar = foo + 1,
foo = 1;
will produce bar === NaN
, just like you stated, because the first thing that will happen is bar will be initialized as foo + 1
, where foo
is technically undefined
.
tl;dr Yes.
Upvotes: 2
Reputation: 921
The difference between
// Case 1
var foo = 1,
bar = foo + 1;
and
Case 2
var bar = foo + 1,
foo = 1;
is that in the first case foo is already defined as 1 so your operation is 1+1 In the second case the moment you define bar, foo is still undefined. Although it is already declared.
In JS all declaration will happen before the program runs. So even if all your var statements are at the bottom of you code it would work. See here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting
Upvotes: 1