Functions

In programming it is common to have chunks of code which you need to use over and over again. Sometimes they do the same job every time but they can also do different things each time (depending on conditions). These chunks have different names but in JavaScript and PHP they are called functions.

Other names used include procedure, method, routine, subroutine or subprogram. In all cases they are chunks of code kept separate from the main program. They are then "called" from the main program when needed.

A typical example would be a function which displayed a Web page element. The function might be called many times. Each time it was called the position, colour or size of the object might change but displaying it would need the same lines of code each time. Rather than repeating the lines every time they are needed the function can be called as needed.

You can send data to a function (known as a parameter). In the above example that might be the size, colour and location of the HTML element. You can also receive data back from the function (known as returning data and done in both PHP and JavaScript with the RETURN key word. The data you RETURN could be a simple success or falure message for error handling or could be the result of calculations done in the function.

Functions mean less code and more efficiency. They can also make the flow of code easier to understand. Take this plain English example of the lines of a program:

start of function fred:
	receive the number to be changed
	double the number provided
	return the answer
end of function fred

read a number from an HTML form and send it to the function fred
read another number from an HTML form and send it to the function fred
read a third number from an HTML form and send it to the function fred
        

Rather than having to write the three lines of code in the main block of code they are placed at the top and so only appear once. The function is parsed (converted to a form that will run) just once but is used three times.

submit to reddit Delicious Tweet