Argument coalescing

OSCC · JavaScript, Type · Sep 15, 2020

Returns the first defined, non-null argument.

  • Use Array.prototype.find() and Array.prototype.includes() to find the first value that is not equal to undefined or null.
const coalesce = (...args) => args.find(v => ![undefined, null].includes(v));
coalesce(null, undefined, '', NaN, 'Waldo'); // ''

Would you like to help us improve 30 seconds of code?Take a quick survey

Recommended snippets