What are JavaScript Nested Functions?

JavascriptWeb DevelopmentFront End Technology

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>
raja
Published on 16-Feb-2018 12:15:27
Advertisements