JavaScript: What Are Functions

¤ Functions

The most basic purpose of a function is to contain code.
Once we have defined a function, we can call it from anywhere, and any number of times.

In JavaScript, we do not have to define the function before we use it
For example, this is legal:

hello();
function hello() {
document.write(\\\\'Hello\\\\');
}

The code for a function MUST be contained by curly brackets { }, even if the code is only one line. So,

function hello() document.write(\\\\'Hello\\\\');

is not legal JavaScript, although it looks like it should be.


A function can be given any user defined name.
Function names CANNOT contain spaces and special characters other than underscore (_)
In the alert box example the function is called showAlert.
You can all your function anything like coolFunction etc.

¤ Parameters

A function\\\\'s advanced features are that it can take parameters and return values.

Take parameters means that we can pass variables to a function for the function to work on.
We can also pass a list of parameters to a function, and we do not need to pass all of them, although we must be precise about their order.

Functions have another quirk, which is that they can house local variables. A local variable is a variable that cannot be seen outside its scope, and behaves independently from other variables of the same name.
To declare a local variable, we use the var keyword.