Could any one explain how this function alert, when more no of brackets of parameters are passed. I could not able to understand it clearly.
function sum(a) {
The first time your function is called, the first value is stored in sum
. After that function f(b)
will be returned, maintaining the provisional result in sum
. With each consecutive call you execute function f
- you perform sum += b
and return f again. If a string context is required (such as in the alert
, or a console.log
) f.toString
is called instead, returning the result (sum
).
function sum(a) {
var sum = a
function f(b) {
sum += b
return f //<- from second call, f is returned each time
// so you can chain those calls indefinitely
// function sum basically got "overridden" by f
}
f.toString = function() { return sum }
return f //<- after first call, f is returned
}
Explanation:
alert( sum(6)(-1)(-2)(-3) ) // 0
/\ function sum called, f returned
/\ the returned function f is called, f returns itself
/\ again
/\ and again
/\ at last, alert() requires string context,
so f.toString is getting invoked now instead of f