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:
- Count the occurrences of array elements
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 }- Split an array into chunks
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]]More
