JS Function With Two Parentheses and Two Params

后端 未结 4 1549
隐瞒了意图╮
隐瞒了意图╮ 2020-12-15 09:16

I\'m trying to understand how a function works that is run with two parentheses and two parameters. Like so:

add(10)(10); // returns 20

I k

4条回答
  •  旧时难觅i
    2020-12-15 10:07

    Welcome to the wonderful world of first order functions

    In JavaScript, a function can return a function since a function is just another object. A simple implementation is something like:

    function add(x){
        return function addOther(y){
            return x + y;
        };
    }
    

    This is possible because of closures and first order functions.

    This also lets you do partial application, libraries like Ramda utilize this to great extent.

    var addThree = add(3)
    addThree(5); // 8
    

提交回复
热议问题