There are many occasions when we get to find out the first non-null or non-undefined argument passed to a function. This is known as coalescing.
Approach 2: We can use the ES6 alternative to the above method to achieve a similar effect. Using Rest Parameters in ES6, we collect all the arguments in the args iterable. We pass a fatty arrow function as a callback to the find method, that iterates over each element of args. We use a throwaway variable in the _ identifier as the element identifier in the callback to the find method. Finally, we use the includes() method to check if the element identified by _ in the callback belongs to either null or undefined. The first element that does not meet the test is our output.
Use Cases of Coalescing
Now that we have seen how to implement Coalesce, let’s discuss what are some of its use cases.
Use Case 1: Filling up for null/undefined values in an array of objects
Example: Let us say you have a Product Catalog with lots of Product Listings. Each product has a description and a summary. You want to display the descriptions and summaries by pulling the data out of this database. In such a case you can use Coalescing with two arguments, the summary value and a truncated description value to fill in when the summary is absent.
Output: With coalesce, if the value of summary is present it will be displayed. In case the summary is missing (null or undefined), the coalescing function will pick the second argument and display a truncated description in the summary field.
ID = 1 Description = The best in class toaster that has 140 watt power consumption with nice features that roast your bread just fine. Also comes bundled in a nice cute case. Summary = Get world class breakfasts ID = 2 Description = A massager that relieves all your pains without the hassles of charging it daily or even hourly as it comes packed with Li-Ion batteries that last upto 8 hrs. Summary = Warm comfort for your back ID = 3 Description = An air conditioner with a difference that not only cools your room to the best temperatures but also provides cleanliness and disinfection at best in class standards Summary = An air conditioner with a difference that not ...
Use Case 2: Filling up values in case of missing numeric values in expressions to perform computations
Example: Say you have an array of monthly incomes for a year with a few missing values. Now, you want to find the total annual income, You decide to substitute a base default value of 1000 for the months in which data is missing. We apply the reduce method on the monthly data array. We store the sum over each iteration in the accumulator with a slight twist. We apply to coalesce on the current item and add either the monthly income (if present) or the default value (if monthly income is null or undefined) to the accumulator.
Yearly income equals 8689