JavaScript Function Example

The following example illustrates how a JavaScript function is written. The function declaration, function name and parameters enclosed with brackets must be on a single line.

Multiple functions can exist in the same source file.

 

function concat ( value1, value2 )

{

    return value1 + value2 ;

}

 

function startDate ( type )

{

    if ( type == 'A' )

    {

        return "30-1-2006" ;

    }

 

    return "23-4-2005" ;

}

 

JavaScript is a loosely typed language.

That does not mean that it has no data types, just that the value of a variable does not need to have a particular type of value assigned to it nor does it need to always hold the same type of value.

JavaScript will freely type-convert values into a type suitable for (or required by) the context of the variable's use.

JavaScript being loosely typed and willing to type-convert still does not save you from needing to think about the actual types of values that you are dealing with.

A problem arises from the dual nature of the + operator used for both numeric addition and string concatenation. The nature of the operation performed is determined by the context. If both operands are numbers to start with, the + operator performs addition, otherwise it converts all of its operands to strings and does concatenation.

The mapping engine passes all values to the JavaScript function as String data types.

It is best to covert parameter values to their required data types.

There are several JavaScript functions such as parseFloat, parserInt and the Number object that can be used to convert String values to number values. Also number variables have several built-in functions such as toFixed and toPrecision that allow formatted values to be returned.

 

 value = Number ( value )

 value = parseInt ( value )

 value = parseFloat ( value )

 

The following example illustrates these functions.

 

function changeit ( value )

{

    value = Number ( value ) ;

 

    if ( value > 100 )

    {

        value = value - 100 ;

    }

 

    return value.toFixed ( 2 ) ;

}