Not sure how having a function within a function works

function multiple(x) {
    function fn(y) {
        return x * y;
    }
    return fn;
}
 
var triple = multiple(3);

triple(2); // returns 6

I’m not sure how this function works and I was wondering if someone could help me decipher it. I understand that assigning the function the value of 3 assigns 3 to x meaning it will be multiplied by y but I’m not sure how assigning the variable “triple” the value of 2 allows that to be assigned to y and thus multiplied by 3. There doesn’t seem to be any way to assign the y value at all, this function works but I have no idea how.

It works because of closure. When multiple(3) is called, the value of x (3 in this case) will remain 3 when the fn function is returned. By assigning the result of calling multiple(3) to the variable triple, triple really just becomes the same as if it was defined as the following:

function triple(y) {
  return 3 * y;
}

You actually can accomplish the same thing without the intermediate function named triple. You can simply call multiple like:

multiple(3)(2); // returns 6

If you can handle a little bit of JS jargon, this article explains it:

http://benalman.com/news/2012/09/partial-application-in-javascript/

It’s basically a combination of various different concepts:

  • Partial application
  • Higher-order functions
  • Functional programming
  • Closures
  • Functions as first-class objects

What happens is that you return a function that will require a variable after the execution of the function that held that variable (the execution of multiple(3)) is over si the engine kinda says aight this variable stays available even though the thing that produced it left and didn’t say goodbye just because someone else needs it. This only works within the same scope of course, which means only works within the context of the outermost function down to the innermost function stack frame. Remember that functions can access outside variables but outer functions can’t access inner functions’ variables so it kinda works like polarized glass.

Thanks for getting back to me on that.