How to define functions inside a function body in JavaScript?


To achieve what you want, use JavaScript Closures. A closure is a function, which uses the scope in which it was declared when invoked. It is not the scope in which it was invoked.

Example

Let’s take your example and this is how you can achieve your task. Here, innerDisplay() is a JavaScript closure.

Var myFunction = (function () {
   function display() {
      // 5
   };
   function innerDisplay (a) {
      if (/* some condition */ ) {
         // 1
         // 2
         display();
      }else {
         // 3
         // 4
         display();
      }
   }
   return innerDisplay;
})();

Updated on: 07-Jan-2020

113 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements