Copyright © tutorialspoint.com

JavaScript Nested Functions

previous next

Advertisements


Prior to JavaScript 1.2, function definition was allowed only in toplevel 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 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:

Following is the example where we have nested two functions. This may be a bit confusing but it works perfectly fine:

<script type="text/javascript">
<!--
function hypotenuse(a, b) {
   function square(x) { return x*x; }
   
   return Math.sqrt(square(a) + square(b));
}
//-->
</script>

Note: Here we are using a function sqrt from Math class. We will see it when we will discuss about Objects.

Now you can call this function in usual way as follows:

<script type="text/javascript">
<!--
hypotenuse(1, 2);  // This will produce 2.2360
//-->
</script>

To understand it in better way you can Try it yourself.


previous next

Copyright © tutorialspoint.com