JavaScript From Beginner To Advanced

0% completed

Previous
Next
JavaScript - Currying

Currying is a transformative technique in functional programming, where a function with multiple arguments is converted into a sequence of functions, each taking a single argument. This method breaks down complex functions into simpler, unary functions, making them more modular and easier to manage. Currying is particularly useful in JavaScript for scenarios where function configurations need to be reused or preset.

Syntax of Currying

To understand the basic concept of currying in JavaScript, consider a simple transformation of a bi-argument function into a curried function:

Javascript
Javascript
. . . .

Explanation:

  • Curried Version (curriedFunction(a)): This function takes the first argument a and returns another function, which expects the second argument b. The final computation, here the addition, happens only when the second function is called.
  • The inner function returned by curriedFunction(a) effectively captures a in its closure, allowing it to be used later when b is provided.

Example: Currying a Function

To illustrate currying, let’s apply it to a simple add function.

Javascript
Javascript

. . . .

Explanation:

  • add(x, y): A straightforward function to add two numbers.
  • curryAdd(x):
    • Takes the first parameter x and returns a new function scoped to that x.
    • The inner function takes another parameter y, and when called, it executes add(x, y).
  • Using Curried Function:
    • const addFive = curryAdd(5); creates a new function that adds 5 to any number it receives.
    • addFive(3) calls this new function with 3, resulting in 8, demonstrating how currying facilitates partial application of functions.

Why Use Currying?

  • Reusability: Currying allows you to create a new function by fixing some parameters of the existing one. This partial application makes it easy to generate new functions on the fly based on old functions but with fewer parameters.
  • Function Composition: Curried functions are much easier to compose into new functions, enhancing the development of higher-level functions from basic ones.
  • Delayed Execution: Currying helps in delaying function execution until all necessary arguments have been provided, which is particularly useful in event handling and asynchronous programming.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next