Search code examples
javascriptcurrying

What’s the use of an arrow function that returns an arrow function?


I saw a weird function that looked something like:

const x = (a) => (b) => a + b;

console.log(x(1)(2))

The output is 3, I understand that it's a function returning a function and both a and b are in the same scope but the questions I have are:

  1. How could this be used in real life?
  2. What's the advantage of not using a function with 2 parameters and using this instead (for a one-line function)?

Solution

  • With this closure, you could get a function with a constant value for later adding.

    1. How could this be used in real life?

    You could take the returned function for a mapping of an array.

    1. What's the advantage of not using a function with 2 parameters and using this instead (for a one-line function)?

    It's a cleaner and functional approach.

    const
        x = a => b => a + b,
        add5 = x(5);
    
    console.log([1, 2, 3].map(add5));