← Back toFront-end tips

Shorten codes with the comma operator

Written byPhuoc Nguyen
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) {
result = value;
} else {
result = other;

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

Shorten an arrow function

const arrowFn = (arg) => {
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

If you found this post helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

Questions? 🙋

Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
Ask me questions

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