Did you know you could do this in JS?

let n = (0, 1);

console.log(n); // 1

And this?

let n = 0;

n = (n++, n++, n);

console.log(n); // 2

And this?

// ๐Ÿ˜’
if (x) {
  foo();
  return bar();
} else {
  return "baz";
}

// ๐Ÿ˜
return x ? (foo(), bar()) : "baz";

And this?

// ๐Ÿ˜’
const f = x => { x[0]=42; return x; };

// ๐Ÿ˜
const g = x => (x[0]=42, x);

At first glance, this seems pretty useless outside of code golf. But I personally find it helpful for a few cases.

Quick Logging

Sometimes I want to log something deep in the code without disturbing the general structure:

// before
function f(x) {
  return x ? "left" : "right";
}

// after
function f(x) {
  return x ? (console.log("left", x), "left") : "right";
}

Without the comma-operator, we wouldโ€™ve had to completely disassemble the ternary-statement into an equivalent if-statement.

Making Returnable If-Statements

// before
let x;
if (n > 0) {
  f();
  x = "left";
} else {
  x = "right";
}

// after
const x = n > 0 
  ? (f(), "left") 
  : "right";

Itโ€™s nice that the code is smaller, but the real benefit of this example is that we donโ€™t need a mutable x variable polluting our scope! I personally find the ternary much safer and easier to read here.