0

I am really confused about the JavaScript COMMA. Here, I have a variable that is assigned to two values inside of parenthesis. The two values are separated by a JavaScript COMMA. When console.log the variable, I only get back the second value.

For Example:

var datum = ('NAD83', 'NAD84');
console.log(datum) // => NAD84

Why does this happen?

Abulurd
  • 896
  • 3
  • 12
  • 31
  • A variable can only have one value, what are you trying to do? – Barmar Feb 13 '17 at 07:35
  • 1
    You get back the *second* value, not the first. – Barmar Feb 13 '17 at 07:36
  • The question is, why is the second value assigned by default? I am just trying to understand the logic behind this. – Abulurd Feb 13 '17 at 07:36
  • Because that's what the comma operator does, it evaluates both operands and returns the second one. – Barmar Feb 13 '17 at 07:37
  • 1
    `,` here is a sequence operator that evaluates all operands and returns the last one. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator – Yury Tarabanko Feb 13 '17 at 07:37
  • I did read through the MDN piece but I am still bit confused as to why this would be done. Why would you even assign the first value if it will not be returned at all? -thanks – Abulurd Feb 13 '17 at 07:43
  • "first value" might be an expression that has side effects. `let x = 0; let y = (x+=1, x); console.log(x, y);` – Yury Tarabanko Feb 13 '17 at 07:50

0 Answers0