The process of finding the first argument that is neither null nor undefined in JavaScript is known as coalescing. We can implement a coalesce() function that accepts multiple arguments and returns the first non-null and non-undefined value.
- Returns the first value that is neither null nor undefined.
- Ignores null and undefined values.
- Returns undefined if all provided values are null or undefined.
Approach 1: Using Loop Traversal
The idea is to iterate through all the arguments and return the first argument that is neither null nor undefined. The != null comparison handles both values.
Example: Finds the first non-null and non-undefined value using a loop.
function coalesce() {
// Loop through all the arguments
for (let i = 0; i < arguments.length; i++) {
// Return the first non-null and non-undefined value
if (arguments[i] != null) {
return arguments[i];
}
}
}
// Driver Code
console.log(coalesce(null, undefined, "First", 1, 2, 3, null));
Output
First
Approach 2: Using ES6 find() with Rest Parameters – O(N) Time and O(N) Space
The idea is to use rest parameters to collect all arguments into an array. The find() method then searches for the first value that is neither null nor undefined.
Example: Uses find() to return the first non-null and non-undefined value.
const coalesceES6 = (...args) =>
args.find(value => value != null);
// Driver Code
console.log(coalesceES6(null, undefined, "Value One", 1, 2, 3, null));
Output
Value One
Use Cases of Coalescing
Coalescing is useful when a value may be missing and we need to provide a suitable fallback.
Use Case 1: Providing a fallback value when an object property is null or undefined.
Example: Uses the product description as a fallback when the product summary is unavailable.
const coalesce = (...args) =>
args.find(value => value != null);
// Display product details with a fallback summary
function displayProdCat(products) {
for (const product of products) {
console.log(`ID = ${product.id}`);
console.log(`Description = ${product.desc}`);
// Use summary if available, otherwise use description
const summary = coalesce(
product.summ,
product.desc.slice(0, 50) + "..."
);
console.log(`Summary = ${summary}`);
}
}
// Product data
const products = [
{
id: 1,
desc: "Best in class toaster with 140W power.",
summ: "Get world class breakfasts"
},
{
id: 2,
desc: "Massager with Li-Ion battery lasting 8 hours."
}
];
// Display product details
displayProdCat(products);
Output
ID = 1 Description = Best in class toaster with 140W power. Summary = Get world class breakfasts ID = 2 Description = Massager with Li-Ion battery lasting 8 hours. Summary = Massager with Li-Ion batte...
Use Case 2: Providing default values for missing numeric data during calculations.
Example: Uses 1000 as the default monthly income when a value is missing.
const incomeFigures = {
default: 1000,
monthWise: [1200, , 600, 2100, , 329, 1490, , 780, 980, , 1210]
};
const coalesce = (...args) =>
args.find(value => value != null);
function yearlyIncome(incomeFig) {
// Use default value for missing income
return incomeFig.monthWise.reduce(
(total, inc) =>
total + coalesce(inc, incomeFig.default),
0
);
}
console.log(
`Yearly income equals ${yearlyIncome(incomeFigures)}`
);
Output
Yearly income equals 8689
Note: In this example, the missing array elements are treated as undefined, so coalesce() replaces them with the default value of 1000.