Javascript-Lesson 5

Functions continued

Calling a function

Some functions produce a result that is used by your script. They are called thus:
result = function_name ( var1, var2 and so on )
If a function does something but has no result to pass back to the script that is calling it, they are called:
function_name ( var1, var2 and so on )

The structure of a function

Functions exist between script tags in the head section of a page.
<script type="text/javascript">
functionfunction_name ( var1, var2, and so on )
{

The script that makes up the function.
}
</script>
If the function is returning a result the last line of the script should be:
return result_var;

Note

warning

If no variables are to be passed to a function the round brackets are left empty, but they should be included.

Loops

Introduction to loops

There is often a need for a section to repeated a number of times; either a fixed number of times or until a condition is met. The javascript 'for loop' and 'while loop' cover this.

The 'for' loop

The javascript 'for' loop is used to repeat a section of code a fixed number of times. The 'for' loop goes something like this:
for ( var = start_value; var = end_value; var = var + increment )
{

   code to be executed
}

Previous Lesson previous lesson next lesson Next Lesson