Tuesday, December 31, 2024
Google search engine
HomeLanguagesJavascriptHow to get the first non-null/undefined argument in JavaScript ?

How to get the first non-null/undefined argument in JavaScript ?

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 1: We can implement coalescing in pre-ES6 JavaScript by looping through the arguments and checking which of the arguments is equal to NULL. We then return the argument that is not NULL immediately.

Example:

Javascript




<script>
function coalesce() {
  for (let i = 0; i < arguments.length; i++) {
    if (arguments[i] != null) {
      return arguments[i];
    }
  }
}
  
console.log(
  coalesce(null, undefined, "First",
           1, 2, 3, null)
);
</script>


Output:

First

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.

Example:

Javascript




<script>
const coalesceES6 = (...args) =>
  args.find(_ => ![null,undefined].includes(_)
);
  
console.log(
  coalesceES6(null, undefined, "Value One",
              1, 2, 3, null)
);
</script>


Output:

Value One

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.

Javascript




<script>
let products = [
  {
    id: 1,
    desc: `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.`,
    summ: `Get world class breakfasts`,
  },
  {
    id: 2,
    desc: `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.`,
    summ: "Warm comfort for your back",
  },
  {
    id: 3,
    desc: `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`,
    summ: null,
  },
];
  
const coalesceES6 = (...args) =>
  args.find((_) => ![null, undefined].includes(_));
  
function displayProdCat(products) {
  for (let product of products) {
    console.log(`ID = ${product.id}`);
    console.log(`Description = ${product.desc}`);
    let summProd =
      coalesceES6(product.summ,
                  product.desc.slice(0, 50) + "...");
    console.log(`Summary = ${summProd}`);
  }
}
  
displayProdCat(products);
</script>


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.

Javascript




<script>
const incomeFigures = {
  default: 1000,
  monthWise: [1200, , 600, 2100, , 329,
              1490, , 780, 980, , 1210],
};
  
const coalesceES6 = (...args) =>
  args.find((_) => ![null, undefined].includes(_));
  
function yearlyIncome(incomeFig) {
  return incomeFig.monthWise.reduce(
    (total, inc) => total +
      coalesceES6(inc, incomeFig.default)
  );
}
  
console.log(
  `Yearly income equals 
  ${yearlyIncome(incomeFigures)}`
);
</script>


Output:

Yearly income equals 8689

RELATED ARTICLES

Most Popular

Recent Comments