The comma operator

The comma operator (a, b) accepts a left-side and right-side operand and will always evaluate to its right-side operand. It is sometimes not considered an operator since it does not technically operate on its operands. It's also quite rare.

The comma operator should not be confused with the comma we use to separate arguments when declaring or invoking a function (for example fn(a,b,c)), the comma used when creating array literals and object literals (for example [a, b, c]), or the comma used when declaring variables (for example let a, b, c;). The comma operator is distinct from all of these.

It's most commonly seen in the iteration statement portion of a for(;;) loop:

for (let i = 0; i < length; i++, x++, y++) {
// ...
}

Note how three increment operations are occurring in the third statement (which occurs at the end of each iteration in a conventional for(;;) statement), and that they are each separated by a comma. In this context, the comma is used merely to ensure that all of these individual operations will occur, regardless of each other, within the context of a singular statement. In regular code outside a for(;;) statement, you would likely just have these each dedicated to their own line and statement, like so:

i++;
x++;
y++;

However, due to the constraints of the for(;;) syntax, they must all exist within a singular statement and so the comma operator becomes necessary. 

The fact that the comma operator evaluates to its right-side operand is not important in this context, but in other contexts, it may be important:

const processThings = () => (firstThing(), secondThing());

Here, processThings, when invoked, will first call firstThing and then secondThing and will return whatever secondThing returns. It is therefore equivalent to the following:

const processThings = () => {
firstThing();
return secondThing();
};

It is rare to see the comma operator used, even in scenarios like this, as it tends to unnecessarily obscure code that could be more clearly expressed. It's useful to know that it exists and how it behaves, but we shouldn't expect it to be an everyday operator.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.33.235