Before JavaScript 1.2, function definitions were only allowed in top-level global code, but JavaScript 1.2 can nest function definitions in other functions.
Still existing function definitions can be looped or restricted within conditions without appearing. These restrictions on function definitions apply only to function declarations and function statements.
Function literals (another feature introduced in JavaScript 1.2) may appear in any JavaScript expression, which means they can appear inside if else statements.
Example:
Here are examples of our two nested functions. This can be a little confusing, but it works perfectly:
<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 the sqrt function from the math class.
Now, this function can be called in the usual way as follows:
<script type="text/javascript"> <!-- hypotenuse(1, 2); // This will produce 2.2360 //--> </script>