[JavaScript]
[Previous page] [Section contents page] [Next page]
Functions

A function is a block of code that has been given a name, so that it can be called to execute that code at any time. Functions may be called with parameters that are used by the code contained in the function. The basic syntax of a function is as follows:

	function name ( parameters ) {
	code to be executed
	}
	
	Example
	
	function writeURL ( URL ) {
	document.write('The URL for this page is: ' + URL)
	}
	

There is no point in creating functions for code that is to be used only once, of course; the aim is rather to create a block of code that will be called upon to execute repeatedly or under certain conditions. Some situations where you might want to use functions are:

  • to pre-define blocks of code that will be executed when a user performs some action (such as clicking on a link)
  • to define code that will be executed according to whether an if ... else structure results in a true or false condition
  • to define code that will be executed repeatedly by a while or for structure
[Previous page] [Section contents page] [Next page]