Invoke Functions on Arguments

JavaScriptJavaScriptBeginner
Practice Now

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

Introduction

In this lab, we will explore the functionality of invoking multiple functions on given arguments and returning the results. Specifically, we will create a function that takes in multiple functions and returns a new function that applies each of those functions to the arguments it receives. This will help us better understand the use of Array.prototype.map() and Function.prototype.apply() in JavaScript.


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-28405{{"`Invoke Functions on Arguments`"}} javascript/data_types -.-> lab-28405{{"`Invoke Functions on Arguments`"}} javascript/arith_ops -.-> lab-28405{{"`Invoke Functions on Arguments`"}} javascript/comp_ops -.-> lab-28405{{"`Invoke Functions on Arguments`"}} javascript/higher_funcs -.-> lab-28405{{"`Invoke Functions on Arguments`"}} javascript/spread_rest -.-> lab-28405{{"`Invoke Functions on Arguments`"}} end

Invoking Functions on Arguments

To execute code using Node.js, open the Terminal/SSH and type node.

To create a function that invokes each provided function with the arguments it receives and returns the results:

  • Use Array.prototype.map() and Function.prototype.apply() to apply each function to the given arguments.
const over =
  (...fns) =>
  (...args) =>
    fns.map((fn) => fn.apply(null, args));

Example:

const minMax = over(Math.min, Math.max);
minMax(1, 2, 3, 4, 5); // [1, 5]

Summary

Congratulations! You have completed the Invoke Functions on Arguments lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like