Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a comma do in assignment statements in JavaScript?

Tags:

javascript

I found this in a piece of code and i'm wondering what it does? Assign b to x... but what's with the ,c?

var x = b, c;
like image 472
capdragon Avatar asked Mar 05 '12 15:03

capdragon


People also ask

Do you need commas in JavaScript?

In JavaScript, there's a standard comma style for adding commas to our code. For multiple variable variables and constant declarations, we have a line break after a comma. This also applies if we have long expressions in arrays or having a list of properties inside an object.

What is the use of comma operator in Java?

In Java, the comma is a separator used to separate elements in a list in various contexts. It is not an operator and does not evaluate to the last element in the list.

What are the uses of comma and conditional (?) Operators?

The comma operator (,) allows you to evaluate multiple expressions wherever a single expression is allowed. The comma operator evaluates the left operand, then the right operand, and then returns the result of the right operand. First the left operand of the comma operator is evaluated, which increments x from 1 to 2.

What is the purpose of comma operator in C?

The comma operator in c comes with the lowest precedence in the C language. The comma operator is basically a binary operator that initially operates the first available operand, discards the obtained result from it, evaluates the operands present after this, and then returns the result/value accordingly.


1 Answers

That declares two variables, x and c, and assigns value b to variable x.

This is equivalent to the more explicit form*:

var x = b;
var c;

JavaScript allows multiple declarations per var keyword – each new variable is separated by a comma. This is the style suggested by JSLint, which instructs developers to use a single var per function (the error message from JSLint is Combine this with the previous 'var' statement.).

* Actually, due to hoisting it will be interpreted as var x; var c; x = b.

like image 156
bfavaretto Avatar answered Oct 23 '22 17:10

bfavaretto