Shorten codes with the comma operator
Written byPhuoc Nguyen
Created
06 Mar, 2021
Category
Trick
Tags
JavaScript
The comma operator (
`,`
) used in the following form evaluates the left-hand side (`a`
) and returns the value of the right-hand side (`b`
):js
const c = (a, b);
We can use it to shorten codes in some cases.
#Shorten an if statement
js
let result;
if (condition) {
doSomething();
result = value;
} else {
result = other;
}
// Shorten version
const result = condition ? (doSomething(), value) : other;
#Shorten an arrow function
js
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:
js
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 }
js
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 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 🥷.
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