Apply Function When Condition Is Met

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore the concept of higher-order functions in JavaScript and learn how to use them to create more flexible and reusable code. Specifically, we will focus on the when function, which takes a condition and a callback function as arguments and returns a new function that applies the callback only when the condition is met. By the end of the lab, you will have a better understanding of functional programming principles and how to apply them in your JavaScript projects.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic 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`") subgraph Lab Skills javascript/variables -.-> lab-28209{{"`Apply Function When Condition Is Met`"}} javascript/data_types -.-> lab-28209{{"`Apply Function When Condition Is Met`"}} javascript/arith_ops -.-> lab-28209{{"`Apply Function When Condition Is Met`"}} javascript/comp_ops -.-> lab-28209{{"`Apply Function When Condition Is Met`"}} end

Using When Function to Apply Condition

To apply a function when a certain condition is met, use the when function. To start, open the Terminal/SSH and type node.

The when function returns a new function that takes one argument and runs a callback if the argument is truthy, or returns the argument if it is falsy. The function expects a single value, x, and returns the appropriate value based on the pred parameter.

Here's an example implementation of the when function:

const when = (pred, whenTrue) => (x) => (pred(x) ? whenTrue(x) : x);

You can use the when function to create a new function that doubles even numbers:

const doubleEvenNumbers = when(
  (x) => x % 2 === 0,
  (x) => x * 2
);
doubleEvenNumbers(2); // 4
doubleEvenNumbers(1); // 1

Summary

Congratulations! You have completed the Apply Function When Condition Is Met lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like