JavaScript Functions

How to Define a Function

The first thing to consider about functions is how to name them. This will be easy for you to remember because JavaScript follows exactly the same rules for naming functions as it does for naming variables. A function is just another type of variable. The only difference from the other types we have looked at so far is that a function contains code rather than numbers or text strings.

We can assign a value to a function the same way that we do with other variable types. Here are two variations on how to assign a value to a function this way.

var x = Function('a = 2; b = 3; c = 4;');
var x = function() {a = 2; b = 3; c = 4;};

There is a third way of coding functions that doesn’t require us to assign the function code to a variable before we use it. This method is the most commonly used way to define functions.

function x() {
  a = 2;
  b = 3;
  c = 4;

There are disadvantages to the first two methods shown. The main one is that the entire functions are effectively treated as one statement. The method used in the last example is exactly the same function written in a way that makes it easier to split the code over multiple lines. This makes this third alternative the easiest one to use most of the time. There will be times when using one of the other two methods makes the code much easier to write so it is worth remembering that there are three ways of defining functions.

Warning: As functions are really just another type of variable, you need to be careful that you don't give them the same name as another variable. This would have the effect of overwriting the value currently stored in that variable with the value of the function.

go to next section 


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow