# Behaviour of commas within parentheses in Javascript

I have a twofold question which involves something I would consider to be incorrect Javascript code.

How is the following statement interpreted in Javascript, and why?

```
(1,2,3,4)
```

Why is there a difference between these two invocations:

```
var a = (1,2,3,4);
a();
```

which leads to `a`

being equal to `4`

and `Uncaught TypeError: a is not a function`

being thrown, and

```
(1,2,3,4)();
```

which leads to `Uncaught TypeError: (((1 , 2) , 3) , 4) is not a function`

?

How is the following statement interpreted in Javascript, and why?

`(1,2,3,4)`

That’s a *comma operator* expression (actually, a chain of them) wrapped in grouping parentheses. The comma operator is quite unusual: It evalutes both of its operands, then takes the value of the second one as its value, throwing away the value of the first one. You have a chain of them there, so the value of 1 is evaluated, then 2, then 3, then 4, and the result of the comma operator chain is the value 4; the result of the grouped parentheses expression is therefore 4.

Why is there a difference between these two invocations:

`var a = (1,2,3,4); a();`

Because of the syntax of the language. In the first case, it’s clearly not a function call, as there’s no value prior to the first `(`

to call. The parsing rules for a complex language like JavaScript are just that: Complex. The parser is context-sensitive, and knows how to differentiate between grouping parentheses and function-call parentheses.

which leads to a being equal to 4 and Uncaught TypeError: a is not a function being thrown, and

`(1,2,3,4)();`

which leads to Uncaught TypeError: (((1 , 2) , 3) , 4) is not a function?

In both cases, the error message is quoting the expression that yielded the result it then tried to call as a function.

There is an operator in JS (among other languages) called the comma operator. It simply takes two operands, and returns the rightmost one.

```
a = 1, 2; // a now equals 2
```

It is, however, *not* the same comma as the function parameter separator. It is an operator.

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

So, the statement `(1,2,3,4);`

returns `4`

, so `var a = (1,2,3,4);`

means that `a`

is equal to `4`

which, is not a function, thus the error.

Likewise, `(1,2,3,4)`

is just a grouping of comma operators and not a function, thus the second error.