Logical and for Functions

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will be exploring the concept of higher-order functions in JavaScript. Specifically, we will focus on creating a function that checks if two given functions return true for a given set of arguments using the logical and operator. Through this lab, you will gain a deeper understanding of how to manipulate functions in JavaScript and how to use them to write more complex 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-28178{{"`Logical and for Functions`"}} javascript/data_types -.-> lab-28178{{"`Logical and for Functions`"}} javascript/arith_ops -.-> lab-28178{{"`Logical and for Functions`"}} javascript/comp_ops -.-> lab-28178{{"`Logical and for Functions`"}} javascript/spread_rest -.-> lab-28178{{"`Logical and for Functions`"}} end

Using Logical AND with Functions

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

To check if two functions return true for a given set of arguments, use the logical AND (&&) operator.

const both =
  (f, g) =>
  (...args) =>
    f(...args) && g(...args);

The above code creates a new function both that takes two functions f and g as input and returns another function that calls f and g with the supplied arguments and returns true only if both functions return true.

For example, to check if a number is both positive and even, we can use the isEven and isPositive functions with both as shown below:

const isEven = (num) => num % 2 === 0;
const isPositive = (num) => num > 0;
const isPositiveEven = both(isEven, isPositive);
isPositiveEven(4); // true
isPositiveEven(-2); // false

Here, isPositiveEven is a new function that checks if a given number is both positive and even by using the both function with isEven and isPositive as inputs.

Summary

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

Other JavaScript Tutorials you may like