Now let us just solve it for a smaller problem. So take it as sum(1)(2) instead of sum(1)(2)(3)(4) for now. Let us solve it now with the code given below:
In the above example, we have taken sum as a function that takes an argument and this sum function will again return us a function that will take the argument as b. And now the below function which takes the argument will now return me the sum of a and b. This will generally give us the output as 3 to console.
This is generally a smaller problem but suppose we have something like sum(1)(2)(3) then we have to return another function which should take c as an argument. In this, we can see a clear pattern and we want to solve this question recursively.
In the above code, we are taking a sum function which takes an argument a. Now, this sum function will return another function which will take an argument b. And now we are checking whether b exists or not. If the value of b exists then we are returning the sum function again and passing the argument as the sum of a+b. Otherwise, we are just returning the value of an as we are considering a case where the value of b will be an empty argument.
When we console.log(sum(1)(2)(3)(4)()) then the output to the console will be 10 as we have made the function sum function very smart above which helps us to achieve the sum of the pattern given below.