Like a variable, a function must be declared before it can be used. The 'function' keyword is used to define a function. There are three elements of a function that must be defined: the name, the parameter list (if any) and the command block. The syntax for a function definition is:
Syntax: function name(parameter1, parameter2, ... parameter_n) { statements; (optional) return a_Value; } |
The name is what you want to call the function. In the previous example, the name of the function is cube(). The parameter list is a list of placeholders to be replaced with arguments when the function is called. This is a very subtle, confusing and important point to understand. In the example script, the variable 'number' is a parameter. The first time the function is called cube(3), the parameter (number) takes on the value of 3. Later, when the function is called again with an argument of 4 cube(4), the parameter (number) takes on the value of 4. If you want your functions to accept multiple arguments, a comma must separate each argument.
The last element of a function is the code block. Like a code block under an 'if' statement, the code block must be encapsulated in brackets. The program statements define the action of the function. Each time the function is called, the program statements within the code block are executed.