Other ways to define functions in JavaScript

There are three ways of defining functions:

  • the function declaration
  • the function constructor
  • the function expression

The function declaration

This method is what I usually use and what you see explained on this website.

Example:

function() {
     Code for function here
}

You can add parameters, return statements, etc.

The function constructor

The function constructor is a method that has poorer performance when compared with the other two methods so it is not used very often by developers when defining functions. It is evaluated every time it is used rather than being parsed only once.

var FunctionName = new Function (arguments, code for function);

Basically, the function constructor creates a function object in the same way you would create a new instance of an object.

The function expression

The function expression is also known as the function operator.
The difference between the function declaration (the most widely used method) and the function expression is that the function declaration creates a variable with the same name as the function name that can be used outside of the function. The function expression can access the variable by its name only within the function itself.

//Example that works
function SendAlert() {
     var MyVariableNumber = 101;
}

window.alert(MyVariableNumber);

The following code will give an error:

/*This code will give an error
The function name can not be used outside the function*/

var get_func = function SendAlert() {
     var MyVariableNumber = 101;
}

window.alert(MyVariableNumber);

You can use the function expression without a function name to create an anonymous function.

An anonymous function is created and called at the same time in one place only (it is not reused elsewhere in the code).

var MyVariableName = function(parameters) {
     Code for function
}

As you can see, it uses the var keyword but it does not name the function.

One useful use for an anonymous function can be to handle a JavaScript event (for example, a user clicking the mouse).

function DoNotClick() {
     window.alert("Don't click on the page!");
}

document.onclick = DoNotClick;

Leave a Reply