Tutorial — Functions

Functions are “first class citizens” (native objects) in JavaScript. Also, a function combined with the new operator is a new object factory! You an also create anonymous functions and attach them to objects as named methods.

function Function_1 (arguments)
{
    // ...
}

Optional Arguments

Function Formal parameters are filled as–and if–provided by the user. It is not an error in JavaScript to call a function with less or more arguments than it declares. (The function may check and complain. That's what this is about.)

The arguments Array contains any arguments passed:

function Function_2 (arguments)
{
    var  number_of_args = arguments.length;

    for (var ix=0; ix < number_of_args; ix++)
    {
        Print (ix, ": ", arguments[ix]);
    }
    // ...
}

You can test declared arguments to see if they are undefined. If they are, nothing was passed in that argument.

function Function_3 (x_in, y_in)
{
    var  x = (x_in == undefined)? 0: x_in;
    var  y = (y_in == undefined)? 0: y_in;

    // ...
}

Closures

Yes, Virginia, JavaScript can do closures:

// Classic Closure Demo...
function Adder (amount)
{
    var  fn = function (n)
    {
        return (amount + n);
    }
    // Return Adder function...
    return fn;
}
var  a1 = Adder(4);
var  a2 = Adder(10);

Print (a1(0));  // prints '4'
Print (a1(-3)); // prints '1'
Print (a1(4));  // prints '8'

Print (a2(0));  // prints '10'
Print (a2(-3)); // prints '7'
Print (a2(4));  // prints '14'