When you pass an object to console.log(), it calls .toString() in order to print out the value.
Thus,
sum(4)
returns a function. The subsequent call to that function
sum(4)(5)
also returns a function. Then that's passed to console.log(), and the result in the console is
9
It should be noted that the console API is a pretty shaky quasi-standard, and because it's designed as a debugging aid there are some behaviors that can be confusing. In this case however it seems to simply call .toString() without any other "helpful" funny business. If, however, you were to just pass a simple empty object to console.log(), like this
console.log({})
you get (at least from Firebug in Firefox) a helpful interface to navigate the object. That's great if you're debugging something, but if you're trying to see how the language works that behavior can be confusing.
As a final note, the trick in the posted code could be extended so that the function can divulge a numeric result too by adding a .valueOf() method:
function sum (a) {
var sum = a;
function f (b) {
sum += b;
return f;
}
f.toString = function () {
return sum;
};
f.valueOf = function() {
return sum;
};
return f;
}
If you do that, then you get the right answer from
console.log(2 * sum(4)(5))
console.log(sum(4)(5));.console.logcalls thetoStringmethod on functions, at least in Chrome.;) to end statement lines. It makes code far less ambiguous.console.log()will call.toString()...