|
defining a function
There are four parts needed to define a function: the keyword function, the name, the arguments, and the statements of the function. Below is the format of a function.
The function name should be descriptive and define what the function does. Arguments are
incoming values, which the function needs to perform its statements. Some of your functions
may not require incoming values, so the argument list is optional. If you omit the arguments,
the first line of the function will have format:
To call a function, you need to specify the function name followed by a list of the actual
values you are sending to the function, if there are any. You may make a call to the function
from within the JavaScript section of your code or from within the HTML body. The following
examples demonstrate various ways of using functions.
Below is an example of a function whose purpose is to simply print a line. No arguments
are needed. The function call is made within the
Below is a function call from the body of the HTML. Because print_line is a JavaScript
component, the function call needs to be nested inside another set of <script> tags. Without
it, the browser would simply print print_line("I'm printing another line."); onto the screen.
This example also shows how to use an argument in the function. In the function call, I am
sending the string "I'm printing another line." to the function. The function calls this
string "message." It then prints message.
Not only can a function accept incoming values, but it can also return a value back to the function call. In the example below, the function call is the right side of an assignment statement. The variable total gets the value that is returned from the function calc_total. The function call sends three values to the calc_total; 1, 2, and 3. The function renames these values number1, number2, and number3. The variable, answer, gets the sum of the three numbers. The function then returns the value of the variable answer.
|
Intro
|
Variables
|
Statements
|
If then else
|
Loops
|
Objects
|
Functions