I want to write function looks like sum(2)(3)
which outputs 6. I am beginner here and tried some closure example but unable to do so. This is question asked in interview.
Asked
Active
Viewed 114 times
0
-
Please show your code. – str Nov 10 '17 at 14:56
-
**You can acheive this using closures in Javascript.** Learn about [Javascript Closures][1] which are basically nested functions where we can chain functions to many levels until we reach a end, at which point it computes the value and returns the value of all above functions. Variables declared outside of a nested function are also accessible inside the nested function. [1]: https://www.w3schools.com/js/js_function_closures.asp – Kunal Mukherjee Nov 10 '17 at 15:23
1 Answers
2
Your sum function needs to return another function which also takes one parameter that you will pass with second parentheses.
function sum(a) {
return function(b) {
return a + b
}
}
console.log(sum(2)(3))

Nenad Vracar
- 118,580
- 15
- 151
- 176