2

Let's say I'm declaring a list of variables in the following manner:

var a = "value_1"
  , b = "value_2"
  , c = b;

What is the expected value of c? In other words, is the scope of a variable immediately available after the comma, or not until the semicolon?

This is as opposed to the following code snippet, where it is very clear that the value of c will be "value_2":

var a = "value_1";
var b = "value_2";
var c = b;

I thought I'd ask rather than test in a browser and just assume that the behavior will be consistent.

Anson Kao
  • 5,256
  • 4
  • 28
  • 37

2 Answers2

3

See the comma operator:

The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand

So b = "value_2" is evaluated before c = b

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • It isn't the comma operator. If it was, this would work `var a = 'foo', (b = 'bar', c = 'baz')` –  May 30 '12 at 22:41
  • May be a good idea to read the docs you linked: *"Note that the comma in the var statement is not the comma operator..."* –  May 30 '12 at 22:52
  • Also from those docs "Practically, that comma behaves almost the same as the comma operator, though" – Quentin May 30 '12 at 22:54
  • Yes, within the very narrow context of the assignments occurring left to right. Linking to those docs is simply misleading. –  May 30 '12 at 23:08
  • Just came upon this unrelated post - http://stackoverflow.com/questions/7609276/javascript-function-order-why-does-it-matter - which has relevant examples to clarify - basically, the interpreter leaves all assignments until after all declarations in the scope have been run first, and maintains order. – Anson Kao Nov 27 '13 at 22:45
2

It's not really an answer to the question, but when faced with such a choice between two expressions of the same thing, always choose the one which is the less ambiguous.

In your second code snippet, it's clear to everybody what the final state is. With the first one, well, you had to ask a question here to know :) If you come back to the code in a month from now, or if somebody else does, then you'll have to go through the same process of finding out the actual meaning. I don't think it's worth the 6 characters you're saving.

Xavier
  • 1,536
  • 2
  • 16
  • 29