Functions
Functions can play an important role in your JavaScript programs. Functions are a set of statements that are put together for a single purpose. You create a function for blocks of code you might need to re-use throughout your program. Using functions make your program modular and flexible. Also, it will be easier to read and follow through. There are three different ways they can appear when calling them in JavaScript:
- On a line by itself
- Right hand side of equal sign
- In a document.write statement
How they work
Ok, when a function is called upon, the control is transfered to the function and the statements in your function are then executed. Once complete, control returns to the command where you called the function or to the next line.
Return Statement
You use the return statment to return a value back to the main program. Here is how you would use the return statement:
return(<sub>)
Naming your functions
When you name your functions, you want to be sure and make the name unique. The rules are the same when naming your variables. Here i'll show the examples of some functions, and the different ways they can appear.
|
function add(a,b) { add = a + b; return(add); } z = 1; y = 2; x = add(z,y); document.write("1 + 2 = "+x+"<br>"); |
In the code sample above, this function call is on the right hand side of the equal sign. You see how it works? When you call the function (by its name) in parenthesis put in the 2 variables that will take the place of 'a' and 'b' and the statements in between the { and } will be executed using the variables you put in it.
|
function add(a,b) { add = a + b; return(add); } z = 1; y = 2; document.write("1 + 2 = "+add(z,y)+". <br>"); |
This is how you would call the function in a document.write statement. It will work the same as above, its just called differently.
|
function add(a,b) { add = a + b; document.write(add); } z = 1; y = 2; add(z,y); |
This is how you could call a function where its on a line by itself. You just replace the return(); with a document.write that will print your result when you call it (if thats what you desire).
One last bit of information on functions, you can also use them to work with strings, so you're not limited just to use them with numbers or anything. Take, a look at this example:
|
function food(fruit) { document.write(fruit+" are good eating!"); } food("oranges"); food("pears"); food("apples"); |
Understanding it more? The function is food, the identifier 'fruit' is the parameter. So fruit is a string used to print the multiple items. We called the function 3 times.
The possibilities for function are endless, and you can make them as complex or as simple as you wish. From adding number or bolding text, to performing complex arithmetic operations and multiple text manipulations.



