Argument Coalescing in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the concept of argument coalescing in JavaScript. Argument coalescing is a technique used to return the first defined, non-null argument out of a list of arguments. Through practical examples, we will learn how to implement this technique using JavaScript's built-in methods such as Array.prototype.find() and Array.prototype.includes().


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28137{{"`Argument Coalescing in JavaScript`"}} javascript/data_types -.-> lab-28137{{"`Argument Coalescing in JavaScript`"}} javascript/arith_ops -.-> lab-28137{{"`Argument Coalescing in JavaScript`"}} javascript/comp_ops -.-> lab-28137{{"`Argument Coalescing in JavaScript`"}} javascript/spread_rest -.-> lab-28137{{"`Argument Coalescing in JavaScript`"}} end

Using Argument Coalescing

To start coding, open the Terminal/SSH and type node. Argument coalescing is a technique used to return the first defined, non-null argument in a list of arguments. To achieve this, use Array.prototype.find() and Array.prototype.includes() to find the first value that is not equal to undefined or null.

Here's an example of how to use argument coalescing in JavaScript:

const coalesce = (...args) => args.find((v) => ![undefined, null].includes(v));

In the above code snippet, coalesce is a function that takes any number of arguments and returns the first defined, non-null argument. Here's an example of how to use the coalesce function:

coalesce(null, undefined, "", NaN, "Waldo"); // ''

In this example, coalesce is called with a list of arguments that includes null, undefined, an empty string '', NaN, and the string 'Waldo'. The function returns an empty string '' because it is the first defined, non-null argument in the list.

Summary

Congratulations! You have completed the Argument Coalescing lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like