When Is the Comma Operator Useful

When is the comma operator useful?

The following is probably not very useful as you don't write it yourself, but a minifier can shrink code using the comma operator. For example:

if(x){foo();return bar()}else{return 1}

would become:

return x?(foo(),bar()):1

The ? : operator can be used now, since the comma operator (to a certain extent) allows for two statements to be written as one statement.

This is useful in that it allows for some neat compression (39 -> 24 bytes here).


I'd like to stress the fact that the comma in var a, b is not the comma operator because it doesn't exist within an expression. The comma has a special meaning in var statements. a, b in an expression would be referring to the two variables and evaluate to b, which is not the case for var a, b.

What is the proper use of the comma operator?

In your example it serves no reason at all. It is on occasion useful when written as

if(cond)
perror("an error occured"), exit(1) ;

-- then you don't need curly braces. But it's an invitation to disaster.

The comma operator is to put two or more expressions in a position where the reference only allows one. In your case, there is no need to use it; in other cases, such as in a while loop, it may be useful:

while (a = b, c < d)
...

where the actual "evaluation" of the while loop is governed solely on the last expression.

Is it good practice to use the comma operator?

It can be useful in the condition of while() loops:

while (update_thing(&foo), foo != 0) {
/* ... */
}

This avoids having to duplicate the update_thing() line while still maintaining the exit condition within the while() controlling expression, where you expect to find it. It also plays nicely with continue;.

It's also useful in writing complex macros that evaluate to a value.

What does the comma operator , do?

The expression:

(expression1,  expression2)

First expression1 is evaluated, then expression2 is evaluated, and the value of expression2 is returned for the whole expression.

Comma operator in c

Can any one explain how output is 2?

In the statement

a = (1, 2), 3;   

, used is a comma operator.
Due to higher operator precedence of = operator than that of , operator, the expression operand (1, 2) will bind to = as

(a = (1, 2)), 3;  

In case of comma operator, the left operand of a comma operator is evaluated to a void expression, then the right operand is evaluated and the result has the value and type of the right operand.

There are two comma operators here. For the first comma operator in the expression (1, 2), 1 will be evaluated to void expression and then 2 will be evaluated and will be assigned to a.

Now side effect to a has been taken place and therefore the right operand of second comma operator 3 will be evaluated and the value of the expression (a = (1, 2)), 3 will be 3.

What does the comma operator do in JavaScript?

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));

When is the comma in JavaScript considered a comma operator and when is it not?

The comma operator is indeed strange, and it takes some time to get used to the nuances.

In var, const, and let declarations, the comma separates the variables (and their initialization expressions, if any). In that case, without (as you note) parenthesized commas, the comma is only a syntactic separator token. However, inside an initalizer expression that does have commas, then that's the comma operator.

Similarly, in an array initializer, the commas are separators for the array values, but once again parentheses introduce a new expression context.

Same goes for the commas in object initializers and in function calls and function declarations.

It's not always the case that comma operator expressions must be parenthesized. In fact some code minimizers try to replace semicolons with commas (for arcane reasons).

In practice, the most useful purpose of the comma operator is to be able to squeeze more than one expression (generally ones with side-effects) into a slot in some larger syntax that allows for one expression. A for loop is a good example:

for (*expression*; *expression*; *expression*) { ... }

The comma operator would let you do two things in one of those expressions:

for (let i = 0; i < 10; someFunction(i), i++) { ... }

Comma operator in condition of loop in C

Comma operator evaluates i<0 Or i>0 and ignores. Hence, it's always the 5 that's present in the condition.

So it's equivalent to:

for(i=0;5;i++)

Uses of C comma operator

C language (as well as C++) is historically a mix of two completely different programming styles, which one can refer to as "statement programming" and "expression programming". As you know, every procedural programming language normally supports such fundamental constructs as sequencing and branching (see Structured Programming). These fundamental constructs are present in C/C++ languages in two forms: one for statement programming, another for expression programming.

For example, when you write your program in terms of statements, you might use a sequence of statements separated by ;. When you want to do some branching, you use if statements. You can also use cycles and other kinds of control transfer statements.

In expression programming the same constructs are available to you as well. This is actually where , operator comes into play. Operator , is nothing else than a separator of sequential expressions in C, i.e. operator , in expression programming serves the same role as ; does in statement programming. Branching in expression programming is done through ?: operator and, alternatively, through short-circuit evaluation properties of && and || operators. (Expression programming has no cycles though. And to replace them with recursion you'd have to apply statement programming.)

For example, the following code

a = rand();
++a;
b = rand();
c = a + b / 2;
if (a < c - 5)
d = a;
else
d = b;

which is an example of traditional statement programming, can be re-written in terms of expression programming as

a = rand(), ++a, b = rand(), c = a + b / 2, a < c - 5 ? d = a : d = b;

or as

a = rand(), ++a, b = rand(), c = a + b / 2, d = a < c - 5 ? a : b;

or

d = (a = rand(), ++a, b = rand(), c = a + b / 2, a < c - 5 ? a : b);

or

a = rand(), ++a, b = rand(), c = a + b / 2, (a < c - 5 && (d = a, 1)) || (d = b);

Needless to say, in practice statement programming usually produces much more readable C/C++ code, so we normally use expression programming in very well measured and restricted amounts. But in many cases it comes handy. And the line between what is acceptable and what is not is to a large degree a matter of personal preference and the ability to recognize and read established idioms.

As an additional note: the very design of the language is obviously tailored towards statements. Statements can freely invoke expressions, but expressions can't invoke statements (aside from calling pre-defined functions). This situation is changed in a rather interesting way in GCC compiler, which supports so called "statement expressions" as an extension (symmetrical to "expression statements" in standard C). "Statement expressions" allow user to directly insert statement-based code into expressions, just like they can insert expression-based code into statements in standard C.

As another additional note: in C++ language functor-based programming plays an important role, which can be seen as another form of "expression programming". According to the current trends in C++ design, it might be considered preferable over traditional statement programming in many situations.

What does the comma operator (expression, expression) means in Javascript when doing condition evaluation?

My question, what does this expression mean?

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

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

Example:

if (y = f(x), y > x) {
// do something ...
}

This executes first the y = f(x) which sets up a value for y (that depends on x). Then checks if y > x. If True then do something, otherwise do nothing. It is the same as:

y = f(x);
if (y > x) {
// do something ...
}

In your examples:

(true, true & false)
// process `true` (does nothing)
// returns the result of `true & false` => false

(true, true & true)
// process `true` (does nothing)
// returns the result of `true & true` => true

(false, true & false)
// process `false` (does nothing)
// returns the result of `true & false` => false

(false, true & true)
// process `false` (does nothing)
// returns the result of `true & true` => true

Further examples:

(true, true, true, false) // returns false
(false, false, false, true) // returns true

So, in your application code:

if (console.debug(`[NotificationOpenedHandler] Received additionalData:`, e), e.type && e.id) {

Is the same as:

console.debug(`[NotificationOpenedHandler] Received additionalData:`, data);
if(data.type && data.id) {


Related Topics



Leave a reply



Submit