JavaScript brackets (1,2,3,4,5)

I just came across some notation in JavaScript like this:

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

      

This will always return the last value in the above case 5

. I know to use parentheses for namespace for my JavaScript code, but have never seen it used this way.

Is there any benefit to this notation, or is it just some kind of byproduct of JavaScript?

+3


source to share


2 answers


This is the comma operator. Since the states are mdn ( reference ), it always returns a later value. In your example, it doesn't make much sense as it always assigns a = 5

. But consider the following:

for (var i = 0, j = 9; i <= 9; i++, j--) {
    ...
}

      

It is used to increase and decrease in one expression: i++, j--



Edit:

The parentheses in your example are required because this is a variable declaration. In other cases, they can be ignored.

+5


source


Parens are used to group transactions together. This is useful both for prioritizing work (eg x = (2 + 3) * 5 versus x = 2 + 3 * 5) and for making your code easier to read.



I suspect this is more of a comma question. This is done to carry out multiple jobs or operations on one line. Here's a good article about it: http://javascriptweblog.wordpress.com/2011/04/04/the-javascript-comma-operator/

-1


source







All Articles