Friday, 31 August 2018

JavaScript: Nested functions

You can define function inside other function. Embedded function can able to access all the variables defined in enclosing function.

embedded.html
<!DOCTYPE html>

<html>

<head>
    <title>Embedded Functions</title>
</head>

<body>
    <script type="text/javascript">
        //Calculate (b*b - 4*a*c)/2*a 
        function descriminator(a, b, c) {
            return (square(b) - 4 * a * c) / twice(a);

            function square(x) {
                return (x * x);
            }

            function twice(x) {
                return 2 * x;
            }
        }

        document.write("Discriminator of 5, 10, 3 is : " + descriminator(5, 10, 3));
    </script>
</body>

</html>

Open above page in browser, you can able to see following message.

Discriminator of 5, 10, 3 is : 4

Scope of variables
Embedded function can able to access all the variables defined in parent function and any other variable where parent function has access.


Previous                                                 Next                                                 Home

No comments:

Post a Comment