JavaScript Currying Techniques

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 currying in JavaScript. Currying is a technique that allows us to transform a function that takes multiple arguments into a sequence of functions that each take a single argument. Through this lab, you will gain a deeper understanding of how currying works and how it can be applied in your JavaScript 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-28233{{"`JavaScript Currying Techniques`"}} javascript/data_types -.-> lab-28233{{"`JavaScript Currying Techniques`"}} javascript/arith_ops -.-> lab-28233{{"`JavaScript Currying Techniques`"}} javascript/comp_ops -.-> lab-28233{{"`JavaScript Currying Techniques`"}} javascript/spread_rest -.-> lab-28233{{"`JavaScript Currying Techniques`"}} end

Currying a Function

To curry a function, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use recursion.
  3. Check if the number of provided arguments (args) is sufficient.
  4. If yes, call the passed function fn.
  5. If not, use Function.prototype.bind() to return a curried function fn that expects the rest of the arguments.
  6. If you want to curry a function that accepts a variable number of arguments (a variadic function, e.g. Math.min()), you can optionally pass the number of arguments to the second parameter arity.
  7. Use the following code:
const curry = (fn, arity = fn.length, ...args) =>
  arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args);

Here are some examples:

curry(Math.pow)(2)(10); // 1024
curry(Math.min, 3)(10)(50)(2); // 2

Summary

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

Other JavaScript Tutorials you may like