[ Web Proxy ]
URL:
Viewing: https://javascript.info/task/closure-sum [Back]  [Original]

Sum with closures
EN

We want to make this open-source project available for people all around the world.

Help to translate the content of this tutorial to your language!

    Search on Javascript.info:
    Search in the tutorial:
    Light themeDark theme
    DanskEnglishEspaolFranaisIndonesiaItalianoTrkeOzbek
    back to the lesson

    Sum with closures

    importance: 4

    Write function sum that works like this: sum(a)(b) = a+b.

    Yes, exactly this way, using double parentheses (not a mistype).

    For instance:

    sum(1)(2) = 3
    sum(5)(-1) = 4
    solution

    For the second parentheses to work, the first ones must return a function.

    Like this:

    function sum(a) {
    
      return function(b) {
        return a + b; // takes "a" from the outer lexical environment
      };
    
    }
    
    alert( sum(1)(2) ); // 3
    alert( sum(5)(-1) ); // 4

    Web Proxy Viewer  |  New URL  |  Original Page