Comma operator~ Basics ~

Comma operator

I think the comma operator in JavaScript is underestimated. The popular perception is that we use the comma to separate function arguments or items in an array. However, there is another use case.

const page = {
  visits: 42
const newPageView = () => {
  return page.visits += 1, page.visits;

console.log(newPageView()); // 43;
console.log(newPageView()); // 44;

newPageView is a function that wants to increase the visits field and return it. The comma operator evaluates each of its operands from left to the right and returns the last one as a result. That is why the output of the newPageView function is the new value of the property.

Someone will ask when such type of writing is beneficial. The truth is that the comma operator makes sense where we write the code in one line. Like for example, the ternary operator.

const a = () => 'a';
const b = () => 'b';
const isValid = true;
const result = isValid ? (a(), b()) : 'Nope';
console.log(result); // b