A curious usage of commas in JavaScript

By

Understand the comma operator in JavaScript: wrapping expressions like ('a', 'b') evaluates both and returns the last one, a curious trick you can assign.

~~~

In JavaScript, the comma can act as an operator: it evaluates all the expressions you separate with it, and returns the value of the last one.

I recently discovered this curious yet possibly useful thing, and I want to show you how it works.

I mostly use commas to separate properties in an object, or array items. However I never gave much attention to the usage of it inside an expression.

Take this:

('a', 'b')

Both expressions (in this case strings) are evaluated, and this returns the last element, the expression after the last comma. In this example it returns 'b'.

You can assign the value to a variable, like this:

const letter = ('a', 'b')
letter === 'b' //true

Notice the parentheses. They are required here. The comma operator has the lowest precedence of all operators, so without them JavaScript would read the line as a declaration of two variables, and raise a syntax error.

Where is this useful?

You’ll mostly see the comma operator in for loops, when you need to update two counters in one step:

for (let i = 0, j = 10; i < j; i++, j--) {
  console.log(i, j)
}

The i++, j-- part runs both updates on every iteration.

Each expression before the last is evaluated for its side effects, and its value is thrown away. That’s the whole point of the operator: do several things where the syntax only allows one expression.

A pitfall to watch for

This behavior can bite you when a comma ends up where you didn’t mean it. Look at this array access:

const scores = [70, 85]
scores[0, 1] //85

You might expect an error, or some kind of multi-index access. Instead, 0, 1 is the comma operator at work: it evaluates 0, discards it, and returns 1. So you get scores[1].

If you meant to access a nested array, the correct syntax is scores[0][1].

My advice: know that the comma operator exists so you can read code that uses it, but reach for it rarely. Separate statements on separate lines are almost always clearer.

~~~

Related posts about js: