JavaScript - Nested Functions


Advertisements

Prior to JavaScript 1.2, function definition was allowed only in top level global code, but 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.

As we'll discuss later in the next chapter, function literals (another feature introduced in JavaScript 1.2) may appear within any JavaScript expression, which means that they can appear within if and other statements.

Example

Try the following example to learn how to implement nested functions.

<html>
   <head>
      <script type = "text/javascript">
         <!--
            function hypotenuse(a, b) {
               function square(x) { return x*x; }
               return Math.sqrt(square(a) + square(b));
            }
            function secondFunction() {
               var result;
               result = hypotenuse(1,2);
               document.write ( result );
            }
         //-->
      </script>
   </head>
   
   <body>
      <p>Click the following button to call the function</p>
      
      <form>
         <input type = "button" onclick = "secondFunction()" value = "Call Function">
      </form>
      
      <p>Use different parameters inside the function and then try...</p>
   </body>
</html>

Output

javascript_functions.htm

Useful Video Courses

Video

JavaScript Online Training

25 Lectures 2.5 hours

Anadi Sharma

Video

JavaScript for beginners

Best Seller

74 Lectures 10 hours

Lets Kode It

Video

jQuery Masterclass Course: JavaScript and AJAX Coding Bible

72 Lectures 4.5 hours

Frahaan Hussain

Video

JavaScript Masterclass: ES6 Modern Development

70 Lectures 4.5 hours

Frahaan Hussain

Video

Modern JavaScript For Developers

46 Lectures 6 hours

Eduonix Learning Solutions

Video

Data Structures in JavaScript: Master The Fundamentals

88 Lectures 14 hours

Eduonix Learning Solutions

Advertisements