3 ms·
If you're like me, this was a little odd: function g(x) { return function(y) { return x + y; }; } f(1, 2) === g(1)(2); How does this work? Si
by dclowd9901 13y ago
If you're like me, this was a little odd:
function g(x) {
return function(y) {
return x + y;
};
}
f(1, 2) === g(1)(2);
How does this work? Since the function g is itself also returning a function, the call g(x) is itself literally another function address (if you will) awaiting an additional parameter with an invisible (y) on the end.
I have been dabbling in functional programming for a short while now, but this one took me completely by surprise. I had no idea JS would pass a function like that.
- tiglionabbit 13y agoThe way functions work in JavaScript is awesome. Just think of a function as another value a variable can have. This might be more clear if we wrote it as: var g = function(x){ var f = function(y){ return x + y; } return f; } Also because of the magic of Lexical Scoping, the new function f holds onto a reference to the variable x that it saw when it was created. If you run var myfunction = g(5), you effectively get this: var myfunction = function(y) { return 5 + y }