Toniq
Toniq

Reputation: 5006

Javascript var assignment

Is this correct? Does the b assignment belongs to already declared b?

var a, b;
//...later
a = 3, b = a * 4;

Or it needs to be like this?

var a, b;
//...later
a = 3; 
b = a * 4;

Upvotes: 2

Views: 69

Answers (1)

Amit
Amit

Reputation: 46341

Quoting MDN:

The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.

So, b = a * 4 will be evaluated after a = 3 and will result in 12.

The difference between the 2 versions is that the latter consists of an additional statement. If you type these statements one after another in a REPL, you'll see the a = 3 statement evaluated as 3, which won't happen in the former version.

Upvotes: 4

Related Questions