How to get the first non-null/undefined argument in JavaScript ?
Last Updated :
23 Apr, 2021
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
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read