Define Functions

In either form, function definitions begin with the keyword function followed by these components:

  • An identifier that names the function.
  • Apairofparenthesesaroundacomma-separatedlistofzeroormoreidentifiers.
  • ApairofcurlybraceswithzeroormoreJavaScriptstatementsinside.
    function factorial(x) {
        if (x <= 1) return 1;
        return x * factorial(x-1);
    }

Nested Functions

In JavaScript, functions may be nested within other functions. For example:

    function hypotenuse(a, b) {
        function square(x) { return x*x; } 
        return Math.sqrt(square(a) + square(b));
    }

the inner function square() can read and write the parameters a and b defined by the outer function hypotenuse().