Skip to main content

Get the first defined and non null argument

JavaScript version

const coalesce = (...args) => args.find((item) => item !== undefined && item !== null);

// Or
const coalesce = (...args) => args.find((item) => ![undefined, null].includes(item));

TypeScript version

const coalesce = (...args: any[]): any[] => args.find((item) => item !== undefined && item !== null);

// Or
const coalesce = (...args: any[]): any[] => args.find((item) => ![undefined, null].includes(item));

Examples

coalesce(undefined, null, 'helloworld', NaN); // 'helloworld'

Comments