Skip to content

Instantly share code, notes, and snippets.

@codeepic
Forked from PatrickJS/two_invocations.js
Created April 12, 2016 16:35
Show Gist options
  • Save codeepic/3772fefc9fb9110a7389a7c191afde79 to your computer and use it in GitHub Desktop.
Save codeepic/3772fefc9fb9110a7389a7c191afde79 to your computer and use it in GitHub Desktop.
Write a function that adds from two invocations in JavaScript
function addf(x) {
return function(y) {
return x + y;
}
}
addf(3)(4)
-------------------------
function addf(x) {
var func = function(y) {
return x + y;
}
return func;
}
addf(3)(4)
@codeepic
Copy link
Author

The outer function returns an anonymous function (line 2). Functions in JavaScript have lexical scope, meaning that they have access to the variables which were in the same scope when the function was declared. In other words, the function remembers variables that are close to it, when it's being created. So the function from line 2 knows the value of parameter x in line 1.
The interesting bit is this addf(3)(4)
addf returns a function and by using the 2nd set of brackets you instantly pass a parameter into it. You could split this line into two:

var a = addf(3); //because addf returns a function, now you can call a() and pass another value to it
a(4);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment