Wrapping function within a function

Hello all
I wanted to know that what is the advantages of wrapping a function within another function. why should we make our code more complex when we can do it in an easier and shorter way(i.e. with only one function)?
Thanks in advance

Do you have a specific example in mind?

1 Like

For example:

function x(y) {
     "use strict";
     return function(c, d){
           return a + b;

So the purpose of the example you provided is to allow us to call a function when we don’t have all of the variables or arguments yet, and then call the rest of the function later.

So for example:

function sumThree(a) {
   return function(b) {
          return function(c) {
                 return (a + b + c);

The above lets us call function “sumThree” with a minimum of one argument to max of three arguments. That’s useful for two cases. Either we know all three arguments and can call the function with all three immediately:

sumThree(1)(2)(3) //1 + 2 + 3

or we only happen to know one argument right now and can store the rest to call later.

let someVariable = sumThree(1) // returns a function that has 1 as its argument and needs two more arguments. which we can then call with:

someVariable(2)(3) // 1 + 2 + 3

I hope that makes sense!

1 Like