Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a comma do in JavaScript expressions?

People also ask

What is the use of comma in JavaScript?

The comma operator ( , ) evaluates each of its operands (from left to right) and returns the value of the last operand. This lets you create a compound expression in which multiple expressions are evaluated, with the compound expression's final value being the value of the rightmost of its member expressions.

What does a comma do in coding?

In the C and C++ programming languages, the comma operator (represented by the token , ) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type); there is a sequence point between these evaluations.

Are commas necessary in JavaScript?

A comma is not an option It is truly important where you put your comma. Defining an array and enumerate elements, you must separate them with a comma. What you actually can do is omitting values. If you want to have every second entry of an array, but keep the indexes of the array.

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.


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

Source: https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special_Operators/Comma_Operator

For example, the expression 1,2,3,4,5 evaluates to 5. Obviously the comma operator is useful only for operations with side-effects.

console.log(1,2,3,4,5);
console.log((1,2,3,4,5));

Some more to consider:

console.log((0, 9));
console.log((9, 0));
console.log(("foo", "bar"));

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

https://stackoverflow.com/a/3561056/5934465

It should be like this!

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

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator