JavaScript functions

Table of content:

What is a function in JavaScript?

A function is a piece of script within another larger script. A function is use to perform one or multiple tasks according to what code is placed inside it.

Functions can be use to organize a script into parts that accomplish different things. Functions can be reused as many times as you wish by simply calling the function again.

A function needs to be declared with its name and its code. You can also import one or more variables into the function, which are called parameters. In addition you can use return statement to return a value to the main script.

Declaring functions in JavaScript

To declare a function, you use the reserved JavaScript word function, followed by the function name, and a set of parenthesis (indicate whether the function accepts any parameters).


function thefunctionname()

Notes:

  • The reserved word function tells browser that a function is declared.
  • There are some special consideration when naming functions (as in the case of variables).
  • Parenthesis are left empty since the function doesn’t accept any parameters.
  • There is no semicolon to show where the function’s code ends but each line of code within the function ends with a semicolon.
  • The code inside the function is surrounded by curly brackets (see below).


function thefunctionname() {
JavaScript code within the brackets.
}

Naming functions in JavaScript

As in the case of variables, naming functions follows the same rules. See Variables in JavaScript for details.

Adding parameters to a function

Parameters are used to import values from outside the function and they are set on the first line of the function in between parentheses.


function MyFirstFunction (variable1,variable2)

Note:

  • A function can have as few or as many parameters as you wish.
  • Not all parameters have to be used but they have to be separated by comma.
  • Any value brought in as parameter becomes a variable within the function.
  • You can use the parameters assigned to a function as any other variable.


function MyFirstFunction (MyMotorbike, MyCity)
document.write("I ride my "+MyMotorbike+" in "+MyCity);

Adding return statement to functions

A return statement is used to return a specific value to the main script.


function MyFirstFunction () {
var FirstText="I used ";
var SecondText="the return statement.";
var TheResult=FirstText+SecondText;
return TheResult;
}

In this example the first two variables are assigned string values and the TheResult variable is given the value of the addition of those two strings.

Notes:

  • The return statement is placed as the last line of the function before the closing curly bracket.
  • The return statement ends with a semicolon.
  • Not only variable values can be returned, all of the below return statements are valid.


return "This is the return statement.";
return "This is the "+"return statement";
return 77;
return 77+43+29;
return true;
return null;
return;

Calling functions in JavaScript

In order to see a function in action you need to call it. A call to a function is simply the function name followed by a set of parentheses (with or without parameters). It has to end with a semicolon.


MyFirstFunction();

Notes:

  • Functions can be called anywhere in your script.
  • A function can be called inside another function.
  • The function definition should come in script before the function call which means that it is a good idea to place all of your function definitions as close to the beginning of the script as possible.

Using a function for a JavaScript alert

A JavaScript alert is a message box that pops up displaying a message in the browser.

You can create a JavaScript alert with window.alert method.


window.alert("This is an alert.");

You can also use a function to pop-up an alert box.


function MyAlertBox() {
window.alert("This is an alert.");
}
MyAlertBox();

In this example the function MyAlertBox is created to do the job of showing the alert. The alert is shown only when the function is called. In the next example two different alert boxes are created before the alert box of the function.


function MyAlertBox() {
window.alert("This is an alert.");
}
window.alert("This is the first.");
window.alert("This is the second.");
MyAlertBox();

The two window.alert() are executed first then the call to function MyAlertBox() will be displayed.

Note:
Pop-up alerts are annoying and they should be avoided where possible. The example I used is to show how a function call works.

Calling a function from another function

A function can be call within another function. In this way it is easier to control and organize the sequence in which your events will occur.


function Update_MyAlertBox() {
window.alert("This is an update!");
}
function TheCallerAlert() {
Update_MyAlertBox()
}
TheCallerAlert();

The real action happens in the first function Update_MyAlertBox(). The second function, TheCallerAlert(), just calls the first function. The second function is not executed until it is called, which happens on the last line of code. This is what starts the whole sequence.

If you want to have three functions that perform three tasks then you can create the forth function that calls them in the desired order.


function TheAlertOne() {
window.alert("Welcome. This is my site!");
}
function TheAlertTwo() {
window.alert("Let's get in touch. Visit contact page.");
}
function TheAlertThree() {
window.alert("You can also visit my photo album.");
}
function GetOrderedResult() {
TheAlertOne();
TheAlertTwo();
TheAlertThree();
}
GetOrderedResult();

First, I defined the three functions, one for each alert I want to show. The fourth function is an ordered call for the previously created three functions. The last line is the call for the fourth function which is a call for the other three.

Calling functions with parameters

An easier way of doing what I did in the last example is by using parameters instead of creating a function for each alert. You can create a function to do the same thing multiple times but with new information taken from parameters each time.

You can use a variable as a parameter but you can also use a value as a parameter. That means we can have variable parameters and value parameters. Variables are also of two types, global and local variables.

Using global variables

Global variables are variables defined outside of a function so they can be changed anywhere in the script.


var MyMotorbike="Honda PCX";
var PriceOfMyMotorbike="3000";

A global variable can be affected by a function.
Let’s consider the following example:


var MyMotorbike="Honda PCX";
var PriceOfMyMotorbike="3000";
function MyNewMotorbike() {
MyMotorbike="Yamaha Nouvo";
PriceOfMyMotorbike="2500";
window.alert("You need just $"+PriceOfMyMotorbike+" to get a "+MyMotorbike);
}
MyNewMotorbike();
window.alert("You make $"+PriceOfMyMotorbike+" and have a "+MyMotorbike);

The browser outputs two alert boxes with the following text:


You need just $2500 to get a Yamaha Nouvo
You make $2500 and have a Yamaha Nouvo

It looks like you created two new variables inside the function, although they have the same name. Obviously this is wrong! Without var keyword you are not creating new variables inside the function (which will make them local) but you are changing the values of your global variables.

Using local variables

A local variable can be used only within the function in which it is declared.
To declare a local variable you have to place it inside a function and use the var keyword.

Notes:

  • A local variable does not exist outside the function in which it is declared.
  • A local variable can be passed along to another function by using parameters.

To correct the script used previously all we need to do is to add the var keyword to declare the local variables inside the function. Therefor the script will look like this:


var MyMotorbike="Honda PCX";
var PriceOfMyMotorbike="3000";
function MyNewMotorbike() {
var MyMotorbike="Yamaha Nouvo";
var PriceOfMyMotorbike="2500";
window.alert("You need just $"+PriceOfMyMotorbike+" to get a "+MyMotorbike);
}
MyNewMotorbike();
window.alert("You make $"+PriceOfMyMotorbike+" and have a "+MyMotorbike);

The browser output will be:


You need just $2500 to get a Yamaha Nouvo
You make $3000 and have a Honda PCX

Using variables as function parameters

You can use variable parameters in the same circumstances. You can send a global variable along to a function then assign its value to a local variable.


function MyMotorbike(PriceOfMyMotorbike) {
var NewPrice=PriceOfMyMotorbike;
window.alert("You make $ "+NewPrice);
}
var PriceOfMyMotorbike=3500;
MyMotorbike(PriceOfMyMotorbike);

The script begins with MyMotorbike function which takes in the parameter PriceOfMyMotorbike. A local variable, named NewPrice, is created. The line of code in the function assigns the value of PriceOfMyMotorbike to the newly created local variable NewPrice. In this way the global variable can be used without being changed. The function then displays a window alert.

Outside the function, in the script, the variable PriceOfMyMotorbike is assigned a value of 3500. At the end, the script calls the function MyMotorbike(PriceOfMyMotorbike) and send it the value of PriceOfMyMotorbike variable.

This is a quite lengthily example of a way to keep from changing a global variable. It can be done differently.


function MyMotorbike(NewPrice) {
window.alert("You make $ "+NewPrice);
}
var PriceOfMyMotorbike=3500;
MyMotorbike(PriceOfMyMotorbike);

When the function is called the script sends to the function the value of PriceOfMyMotorbike variable. Instead of naming the value “PriceOfMyMotorbike” and assigning it to another variable you simply just use another name within parentheses. In this way the variable NewPrice becomes a local variable inside the function MyMotorbike(). Since the code sends PriceOfMyMotorbike a value of 3500, NewPrice will be 3500.

Using value parameters

You can also send a value as a parameter directly which will be converted into a local variable inside the function without the need to declare a global variable.


function MyMotorbike(NewPrice,NewMotorbike) {
window.alert("You make $"+NewPrice+" and you have a "+NewMotorbike);
}
MyMotorbike(3500,"Honda PCX");

The function call sends two parameters to the function. These two parameters, 3500 and Honda PCX, are read by the function as local variables and used to display the alert with the text “You make $3500 and you have a Honda PCX”.

Another important thing to mention is that parameters are optional. If the parameters are missing the output will be “You make $undefined and you have a undefined”.


function MyMotorbike(NewPrice,NewMotorbike) {
window.alert("You make $"+NewPrice+" and you have a "+NewMotorbike);
}
MyMotorbike();

You can also tell JavaScript to check if the parameters exist before writing the statement to the page. If the parameters exist then the statement will be written on the page, if they don’t exist then the alert will say “Missing the parameters”.


function MyMotorbike(NewPrice,NewMotorbike) {
if (NewPrice && NewMotorbike) {
window.alert("You make $"+NewPrice+" and you have a "+NewMotorbike);
}
else {
window.alert("Missing the parameters");
}
}
MyMotorbike();

Calling functions with return statement

You can assign the result of a function to a variable. In this way the variable gets the value returned from the function and you can use it later in the script.


function GetAllText() {
var text1="I have a ";
var text2="Honda PCX!";
var AddText=text1+text2;
return AddText;
}
var TextAlert=GetAllText();
window.alert(TextAlert);

First we have a function and three local variables. The value of the third variable is basically the values of the first two variables combined. The function GetAllText() returns the value of the third variable. The result of the function GetAllText() is then assigned to the variable TextAlert which is then used to send an alert to the user with the result “I have a Honda PCX!”.

Other ways to define functions

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 doe 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