← Back toFront-end Tips

Shorten codes with the comma operator

Written byPhuoc Nguyen
Category
Trick
Tags
JavaScript
Created
06 Mar, 2021
The comma operator (`,`) used in the following form evaluates the left-hand side (`a`) and returns the value of the right-hand side (`b`):
const c = (a, b);
We can use it to shorten codes in some cases.

Shorten an if statement

let result;
if (condition) {
doSomething();
result = value;
} else {
result = other;
}

// Shorten version
const result = condition ? (doSomething(), value) : other;

Shorten an arrow function

const arrowFn = (arg) => {
doSomething();
return result;
};

// Shorten version
const arrowFn = (arg) => (doSomething(), result);
Here is a few examples of using the comma operator to shorten arrow functions:
const countOccurrences = (arr) => arr.reduce((p, c) => ((p[c] = ++p[c] || 1), p), {});

countOccurrences([2, 1, 3, 3, 2, 3]);
// { '1': 1, '2': 2, '3': 3 }
const chunk = (arr, s) => arr.reduce((a, e, i) => (i % s ? a[a.length - 1].push(e) : a.push([e]), a), []);

chunk([1, 2, 3, 4, 5, 6, 7, 8], 3);
// [[1, 2, 3], [4, 5, 6], [7, 8]]

See also

Questions? 🙋

Do you have any questions? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.

Recent posts ⚡

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn