1

In one quiz I came across the following question:

What is the value of val?

var val = (5, 10, 15);

Despite the fact that I'm quite experienced with JavaScript I have never seen such kind of assignment before and failed to find any information about it on the internet.

What are the use cases and how it actually works?
Thanks in advance.

savchenkoto
  • 151
  • 1
  • 10
  • 1
    Would tell comma operator wins here - 3 evaluations and result is 3rd 15 ? In case there would be square brackets it could be Array, that would sound more reasonable in this case. – Tom Sep 14 '19 at 19:29

1 Answers1

1

In JS, the comma operator (,) evaluates all operands, and returns the last.

So, in your case, it is equivalent to:

var val=15;

The 5 and 10 are evaluated and then silently dropped.

But consider the following:

var i=0;
var val=(i++,15);

console.log(i) //1
console.log(val) //15

The value of i is increased by 1, and it returns 15, combined to a single expression.

FZs
  • 11,931
  • 11
  • 28
  • 41