+ 2
Whats going on here?
I recently got this question in a (javascript) quiz: What is the output of this code? var foo = (a, b) => a + b; var bar = (a, b) => a - b; var sum = (a, b, foo) => foo(a, b); alert(sum(90,-9,bar)); (it's 99 but why?) Can someone explain what's going on here?
3 Answers
+ 5
You are calling the custom function sum.
It takes 3 inputs.
Two variables and a function.
In the definition of sum, the name of the input function is foo, but this foo only exists within the scope of the function definition and does not know about the other foo. Its just saying that whatever function you write in input 3, it will call with variables in a and b.
The two variables gets passed to the function.
In this case sums input is
90, - 9, bar
So sum calls bar(90, - 9)
What bar does is to subtract the second input from the first.
So 90 - (-9)
= 90 + 9
= 99
+ 3
because when function sum arguments are having value , a=90, b=-9 and foo=bar after calling it .
Now bar(90, -9) obviously returns 99.
+ 1
I get it nowđ!
Thanks to both of you!