Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In this case you are supposing that function(1) returns a function, than you are calling this new, anonymous function with an argument of 2.</p> <p>See this example:</p> <pre><code>function sum(a) { return function(b) { return a+b; } } // Usage: window.alert(sum(5)(3)); // shows 8 var add2 = sum(2); window.alert(add2(5)); // shows 7 window.alert(typeof(add2)); // shows 'function' </code></pre> <p>Here we create a function <code>sum</code> that takes one argument. Inside the function <code>sum</code>, we create an <code>anonymous function</code> that takes another argument. This anonymous function is returned as the result of executing <code>sum</code>.</p> <p>Note that this anonymous function is a great example of what we call <strong><a href="http://en.wikipedia.org/wiki/Closure_%28computer_science%29" rel="nofollow noreferrer">closure</a></strong>. A closure is a function that keeps the context in which it was created. In this case, it will keep the value of the variable <code>a</code> inside it, as did the example function <code>add2</code>. If we create many closures, they are independent as you can see:</p> <pre><code>var add3 = sum(3); var add4 = sum(4); window.alert(add3(3)); // shows 6 window.alert(add4(3)); // shows 7 </code></pre> <p>Furthermore, they won't get "confused" if you have similarly named local variables:</p> <pre><code>var a = "Hello, world"; function multiply(a) { return function(b) { return a * b; } } window.alert(multiply(6)(7)); // shows 42 var twoTimes = multiply(2); window.alert(typeof(twoTimes)); window.alert(twoTimes(5)); </code></pre> <p>So, after a call to <code>sum(2)</code> or <code>multiply(2)</code> the result is not a number, nor a string, but is a <code>function</code>. This is a characteristic of <em><a href="http://en.wikipedia.org/wiki/Functional_programming" rel="nofollow noreferrer">functional languages</a></em> -- languages in which functions can be passed as parameters and returned as results of other functions.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload