Reputation: 1340
I use this syntax often but I don't understand why it simply works.
var a = 1, b = a + 1;
console.log(b); // 2
In the event you're declaring a var, after splitting them on a comma, the b
already sees a
as evaluated? Why is that?
Upvotes: 2
Views: 114
Reputation: 154938
It has been defined as such.
First, the definition of the essential terms:
VariableStatement :
var
VariableDeclarationList;
and:
VariableDeclarationList :
VariableDeclaration
VariableDeclarationList , VariableDeclaration
The actual definition which applies to your question is this one:
The production VariableDeclarationList : VariableDeclarationList , VariableDeclaration is evaluated as follows:
Evaluate VariableDeclarationList.
Evaluate VariableDeclaration.
So at the time #2 is executed, #1 has been evaluated already and you can use any effect of it in #2.
Upvotes: 4
Reputation: 423
That's due to how variables are declared in JavaScript. Variable declaration in Javascript happens in two steps. First, the all the variables declared in the current scope are initialized and given the value undefined and after all the variables are declared this way, they are then given their actual value. So your code:
var a = 1, b = a + 1;
is translated to:
var a = undefined;
var b = undefined;
a = 1;
b = a + 1;
This is called hoisting. As all the variables you declare are hoisted at the top of the scope. This allows you to do weird things like:
var a = b; // b = undefined
var b = 0;
Upvotes: 3
Reputation: 23678
It's a bit counter-intuitive but just think of it as equal to this:
var a = 1;
var b = a + 1;
Unlike other languages like Python where multiple assignments operate on the previous values (making swaps easier)
Upvotes: 1
Reputation: 7546
Simply because a gets initialized before b. This process goes from the left to the right.
Upvotes: 2