Overloading Functions in Javascript

Javascript does not support the kind of function overloading you find in languages such as C#. For example in C# you can define two version of a function:

// Double a value.
int DoubleAValue(int Value)
{
...

and

// Double a value, but let the user choose only to double
// if the value is greater than 10.
int DoubleAValue(int Value, bool IfGreaterThan10)
{

You can’t do this kind of overloading in Javascript, but a similar capability can be implemented by exploiting the fact that Javascript doesn’t force callers to specify values for all arguments to a function.

So to implement a kind of overloading, you could write your function in Javascript as:

function DoubleAValue(Value, IfGreaterThan10)
{
...

and callers could decide to call the function with or without the second argument:

var Result = DoubleAValue(10);

and

var Result = DoubleAValue(x, true);

To support the optional argument though, the coder has to implement the function to allow for the second argument not to be specified. There is no way to give a default value to the second argument so the function has to check if the argument is present when called. To do this the function can check whether the argument is undefined …

function DoubleAValue(Value, IfGreaterThan10)
{
    var LocalIfGreaterThan10 = true;

    if (typeof IfGreaterThan10 != 'undefined') {
        // The argument is present on this call. Take the value from the argument.
        LocalIfGreaterThan10 = IfGreaterThan10;
    }

    if (Value <= 10 || LocalIfGreaterThan10) {
        Value = Value * 2;
    }

    return Value;
}

For more Javascript help and tips, see: http://www.sliqtools.co.uk/blog/javascript/writing-javascript-objects-and-adding-element-event-handlers/

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>