logologo

Three-D

☕Sign in

    Recent Post:

    Categories:

    nextjsjavascriptthreejshonoreactjs
    featured post image

    snippets

    featured post image

    What is Currying?

    featured post image

    What is an IIFE?

    What is Currying?

    September 22, 2024

    520

    image

    Think you know it all?

    Take quiz!

    Currying with Arrow Functions

    Currying is a functional programming technique in which a function takes multiple arguments one at a time, transforming a function that takes multiple parameters into a series of functions that each take a single parameter. This allows for more flexible and reusable code.

    How Currying Works

    In currying, a function is transformed so that it can be called multiple times with fewer arguments, returning new functions until all arguments are provided.

    code

    function add(a) {
        return function(b) {
            return a + b;
        };
    }
    
    const addFive = add(5);
    console.log(addFive(3)); // Output: 8

    The add function takes one argument a and returns another function that takes b. The inner function can access a from its lexical scope, allowing us to create a new function addFive that adds 5 to any number.

    Currying with Multiple Arguments

    Currying can be extended to functions that require more than two arguments.

    code

    function multiply(a) {
        return function(b) {
            return function(c) {
                return a * b * c;
            };
        };
    }
    
    const multiplyBy2 = multiply(2)(3);
    console.log(multiplyBy2(4)); // Output: 24

    Here, multiply is a curried function that takes three arguments one at a time. You can first pass 2, then 3, and finally, when you pass 4, it computes 2 * 3 * 4.

    Using Currying in Real Life

    Currying is particularly useful when you need to create functions with preset arguments, allowing for easier and cleaner code

    code

    function greet(greeting) {
        return function(name) {
            return greeting + ", " + name + "!";
        };
    }
    
    const greetHello = greet("Hello");
    console.log(greetHello("Satyendra")); // Output: Hello, Satyendra!

    Here, the greet function is curried, allowing us to create a specific greeting function like greetHello.

    You can also implement currying using arrow functions, making the syntax more concise.

    code

    const add = a => b => a + b;
    
    const addTen = add(10);
    console.log(addTen(5)); // Output: 15

    The same logic applies, but we use arrow functions for a cleaner look.

    Benefits of Currying

    Reusability: Create functions with preset arguments for reuse.

    Function Composition: Combine multiple functions more easily.

    Improved Readability: Makes your code easier to read and understand.