+ 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?

17th Jul 2021, 9:13 PM
gilex
gilex - avatar
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
17th Jul 2021, 10:00 PM
Louis
Louis - avatar
+ 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.
17th Jul 2021, 10:01 PM
Abhay
Abhay - avatar
+ 1
I get it now😀! Thanks to both of you!
18th Jul 2021, 7:04 AM
gilex
gilex - avatar