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
How to Check empty/undefined/null String in JavaScript?
Empty strings contain no characters, while null strings have no value assigned. Checking for an empty, undefined, or null string in JavaScript involves verifying if the string is falsy or has a length of zero. Here are different approaches to check a string is empty or not.1. Using === OperatorUsing
2 min read
How to handle an undefined key in JavaScript ?
In this article, we will try to analyze how we may handle an undefined key (or a property of an object) in JavaScript using certain techniques or approaches (via some coding examples). Firstly let us quickly analyze how we may create an object with certain keys along with their values using the foll
3 min read
How to Detect an Undefined Object Property in JavaScript ?
Detecting an undefined object property is the process of determining whether an object contains a certain property, and if it does, whether the value of that property is undefined. This is an important concept in JavaScript programming, as it helps to prevent errors that can occur when attempting to
3 min read
How to Fix SyntaxError: arguments is not valid in Fields in JavaScript?
A Syntax Error argument is not valid in fields occurs in JavaScript when the arguments object is used improperly within the context of a class field or similar construct where it's not allowed, the arguments object is an array-like object accessible within the scope of a function that contains the v
3 min read
How to Replace a value if null or undefined in JavaScript?
In JavaScript, replacing a value if it is null or undefined involves providing a default value to use when the original value is either null or undefined. This ensures the application has valid data, preventing potential errors or unexpected behavior. Here we have some common approaches: Table of Co
2 min read
JavaScript - How to Get the First Three Characters of a String?
Here are the various methods to get the first three characters of a string in JavcaScript1. Using String.slice() MethodThe slice() method is one of the most commonly used and versatile methods to extract a part of a string. It allows you to specify the start and end positions for slicing the string.
3 min read
How to check for "undefined" value in JavaScript ?
In JavaScript, undefined is a primitive value that represents the absence of a value or the uninitialized state of a variable. It's typically used to denote the absence of a meaningful value, such as when a variable has been declared but not assigned a value. It can also indicate the absence of a re
2 min read
How to get the first key name of a JavaScript object ?
In JavaScript, accessing the first key name of an object involves identifying the initial property defined within that object. This concept is useful when you need to interact with or manipulate object properties in a specific order, particularly when the sequence of properties is relevant.Here we h
2 min read
How to check for null values in JavaScript ?
The null values show the non-appearance of any object value. It is usually set on purpose to indicate that a variable has been declared but not yet assigned any value. This contrasts null from the similar primitive value undefined, which is an unintentional absence of any object value. That is becau
4 min read
How to Get all Elements Except First in JavaScript Array?
Here are the various methods to get all elements except the first in JavaScript Array1. Using for loopWe will use a for loop to grab all the elements except the first. We know that in an array the first element is present at index '0'. JavaScriptconst a1 = [1, 2, 3, 4, 5]; const a2 = []; let k = 0;
4 min read