What are JavaScript Nested Functions?


JavaScript 1.2 allows function definitions to be nested within other functions as well. Still there is a restriction that function definitions may not appear within loops or conditionals. These restrictions on function definitions apply only to function declarations with the function statement. 

Example

You can try to run the following code to learn how to implement JavaScript Nested Functions −

<html>
   <head>
      <script>
         function hypotenuse(a, b) {
            function square(x) { return x*x; }
            return Math.sqrt(square(a) + square(b));
         }
         function secondFunction(){
            var result;
            result = hypotenuse(3,4);
            document.write ( result );
         }
      </script>
   </head>
   
   <body>
      <p>Click the following button to call the function</p>
      <form>
         <input type = "button" onclick = "secondFunction()" value = "Find Hypotenuse">
      </form>
   </body>
</html>

Updated on: 19-Jun-2020

248 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements