Next page | Contents page |

What is a function?

A function is a chunk of program that can be reused, to do something that is required more than once. It is like a black box in that you can pass some values into it and there will be some kind of result. Once it has been written and tested you can forget about its internal workings.

One way to start writing a function is with the keyword function, then make up a name for the function and finally put a pair of brackets. That is what we did for the function run() in the exercise on the previous page.

Javascript has a number of keywords that must not be used as names for anything else. We will meet others soon. (MDN lists such things.)

If some values are to be passed into a function then they are listed inside the brackets, separated by commas. These are called the parameters of the function (sometimes called arguments but we will not go into the difference).

The result of a function may be some effect, such as a shape appearing on the canvas, or it may be a value passed back using another keyword, return.

We will soon see many examples of defining functions, of using them, and of using some pre-defined ones.

Next page | Contents page |