Logical or for Functions

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore how to use the logical or operator to combine two functions and check if at least one of them returns true for a given set of arguments. We will learn how to define a higher-order function that takes two functions as arguments and returns a new function that performs the logical or operation on the results of the input functions. Through examples and exercises, we will gain a better understanding of how to use the logical or operator to write more concise and efficient code.


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-28341{{"`Logical or for Functions`"}} javascript/data_types -.-> lab-28341{{"`Logical or for Functions`"}} javascript/arith_ops -.-> lab-28341{{"`Logical or for Functions`"}} javascript/comp_ops -.-> lab-28341{{"`Logical or for Functions`"}} javascript/spread_rest -.-> lab-28341{{"`Logical or for Functions`"}} end

Using Logical Or for Functions

To start practicing coding, open the Terminal/SSH and type node.

The logical or (||) operator can be used to check if at least one function returns true for a given set of arguments. To do this, call the two functions with the supplied args and apply the logical or operator on their results.

Here's an example implementation of either function:

const either =
  (f, g) =>
  (...args) =>
    f(...args) || g(...args);

And here's an example usage of either function with two functions isEven and isPositive:

const isEven = (num) => num % 2 === 0;
const isPositive = (num) => num > 0;
const isPositiveOrEven = either(isPositive, isEven);
isPositiveOrEven(4); // true
isPositiveOrEven(3); // true

In this example, isPositiveOrEven returns true for both 4 and 3 because isEven returns true for 4 and isPositive returns true for 3.

Summary

Congratulations! You have completed the Logical or for Functions lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like