Last active
September 19, 2023 07:00
-
-
Save PatrickJS/5462522 to your computer and use it in GitHub Desktop.
Write a function that adds from two invocations in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Nice explanation
thanks for explanation! :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:Hopefully it makes more sense now.