This page looks best with JavaScript enabled

Comma operator in Javascript

 ·   ·  ☕ 2 min read

Did you know how to use comma operator in Javascript? A simple , can separate expressions in the same statement, evaluate left-to-right in the expression, pick the right most valid value as the result, and confuse other developers - all within the blink of an eye.

We have discussed about operators when discussing operator precedence. But the no. of uncommon operators are more than the typical bunch.

Oh, and btw, comma has the lowest precedence amongst all operators.

Let us look at a few examples involving comma operator.

1
2
3
4
5
let a = (7, 5);
console.log("a: ", a); // 5

let a = ((b = 1), (c = 2));
console.log("a: ", a); // 2

An example in real world -

1
2
3
4
5
6
7
for (
  var a = 2, fibo = [0, 1];
  a < 5;
  fibo.push(fibo[a - 1] + fibo[a - 2]), a++
);

console.log(fibo); // [ 0, 1, 1, 2, 3 ]

Just imagine comma happening to your production program, and shudder.

But, it’s not all that bad. Sometimes you would have used the humble comma without even realizing its presence.

1
2
3
4
5
let questionsRemaining = 0;

questionsRemaining
  ? (questionsRemaining--, nextQuestion())
  : (examsComplete(), scoreAndExit());

Still think it is bad? Yep - I am totally with you.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things