Negating Predicate Functions 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 negating a predicate function in JavaScript. We will learn how to create a higher-order function that takes a predicate function and returns a new function that negates the original function's output. Through practical examples, we will see how this technique can be useful in filtering arrays or validating input.


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/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28506{{"`Negating Predicate Functions in JavaScript`"}} javascript/data_types -.-> lab-28506{{"`Negating Predicate Functions in JavaScript`"}} javascript/arith_ops -.-> lab-28506{{"`Negating Predicate Functions in JavaScript`"}} javascript/comp_ops -.-> lab-28506{{"`Negating Predicate Functions in JavaScript`"}} javascript/higher_funcs -.-> lab-28506{{"`Negating Predicate Functions in JavaScript`"}} javascript/spread_rest -.-> lab-28506{{"`Negating Predicate Functions in JavaScript`"}} end

How to Negate a Predicate Function in JavaScript

To negate a predicate function in JavaScript, you can use the ! operator. To do this, you can create a higher-order function called negate that takes a predicate function and applies the ! operator to it with its arguments. Here's an example of how to implement negate:

const negate =
  (func) =>
  (...args) =>
    !func(...args);

You can then use negate to negate any predicate function. Here's an example of how to use negate to filter out even numbers from an array:

const isEven = (n) => n % 2 === 0;
const isOdd = negate(isEven);

[1, 2, 3, 4, 5, 6].filter(isOdd); // [ 1, 3, 5 ]

In this example, isEven is a predicate function that checks if a number is even. We then use negate to create a new predicate function called isOdd that checks if a number is odd by negating isEven. Finally, we use isOdd with the filter method to filter out even numbers from the array.

Summary

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

Other JavaScript Tutorials you may like