Search code examples
javascriptfunctionnested

Can you write nested functions in JavaScript?


I am wondering if JavaScript supports writing a function within another function, or nested functions (I read it in a blog). Is this really possible?. In fact, I have used these but am unsure of this concept. I am really unclear on this -- please help!


Solution

  • Is this really possible.

    Yes.

    function a(x) {    // <-- function
      function b(y) { // <-- inner function
        return x + y; // <-- use variables from outer scope
      }
      return b;       // <-- you can even return a function.
    }
    console.log(a(3)(4));