Skip to content

Instantly share code, notes, and snippets.

@PatrickJS
Last active September 19, 2023 07:00
Show Gist options
  • Save PatrickJS/5462522 to your computer and use it in GitHub Desktop.
Save PatrickJS/5462522 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)
@ANDYAMBI
Copy link

Hi, I am beginner in Javascript..It would be great if you could explain how exactly this thing works since i am little confused about it..

@codeepic
Copy link

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);

Hopefully it makes more sense now.

@sarir-karim
Copy link

Nice explanation

@MantasUrb
Copy link

thanks for explanation! :)

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