Functions help organize the various parts of a script into different tasks that must be accomplished.
A function contains code that will be executed by an event or by a call to the function.
Functions can be used more than once within a script to perform their task. Rather than rewriting the entire block of code, you can simply call the function again.

There are two kinds of functions:

1. Declaring Functions

Functions can be defined both in the <head> and in the <body> section of a document. However, to assure that a function is read/loaded by the browser before it is called, it's better to put functions in the <head> section.
The most basic way to define a function is using the word "function", the name of the function followed by two parentheses (where we can add the parameters) and a pair of curly brackets that contain the code of the function.

Function syntax
function functionName(var1, var2, ...) {
 code to be executed
The parameters var1, var2, etc. are variables or values passed into the function. The brackets { and the } defines the start and end of the function.
- A function with no parameters must include the parentheses () after the function name.

Function names are case sensitive, be sure you use the identical name when you call the function.
The word function must be written in lowercase letters.

2. The Return Statement

A return statement is used to specific a value that a function returns to the main script. You place the return statement as the last line of the function before the closing curly bracket and end it with a semicolon.
For example, to return the value of a variable "some_var", the return statement looks like this:
                return some_var; The next function returns the value of a variable 'z' that contain the amount of two parameers (x, y):
function amount(x, y) {
 var z = x+y;
 return z;
- The "amount" is the name of the function, "x" and "y" are the parametres. The function returns the value of "z" variable, that contain the amount of "x" and "y".

3. Calling Functions

After the function is defined, we can call and use it.
You may call a function from anywhere within a page (or even from other pages if the function is embedded in an external .js file). You can even call a function inside of another function.
A function with parameters can be called using the syntax:
functionName(arg1, arg2, ...);
- "arg1", "arg2", ... are the arguments passed to the function.
A function without paramentre with the following syntax:
Note that the function call no longer use the word "function" and braces
In the place of the script where we call a function it's executed the code of that function.

4. Sample scripts with functions

- Example 1 - function without parameter
The JS script of the next example display a text in the web page:
<script type="text/javascript"><!--
function ex1() {
 return document.write("Welcome!");
<script type="text/javascript">
- The function "ex1" was defined in the Head section of the HTML document and then was called in the "Body", where will display the text "Welcome!".

- Example 2 - function with one parameter
The script in the next example opens an Alert window with a text received as an argument of a function.
<script type="text/javascript"><!--
function ex2(text) {
 <input type="button" onclick="ex2('Good morning!')" value="Morning" />
 <input type="button" onclick="ex2('Good afternoon!')" value="Afternoon" />

- This code will return the following effect. Just click the buttons.:
- The text displayed in the Alert pop-up is taken from the argument passed to the function when the function is called.
- "onclick" (la click) is a JavaScript method that specifying the time when the function will be executed.

- Example 3 - function with two parameters
The function in this example opens an Alert pop-up that will display the result of the multiplication of two numbers.
<script type="text/javascript"><!--
function ex3(x,y) { 
 var z = x*y;
 return alert(x+" * "+y+" = "+z)
 <input type="button" onclick="ex3(7, 8)" value="7*8" />
- This code will display the next results:
- When you click the button an alert window will display the result of the 7*8.

Inside the function can be used complex instructions: "for", "if", "while", which may take different decisions depending on the function arguments. It only depends on your knowledge and imagination

• Another way to declare a function is to use the function literal form as a value of a variable.
var variable_name = function(var1, var2, ...) {
 code to be executed
- "var1", "var2" are the parameter of the function.
This is also known as an anonymous function. The term "anonymous" refers to the fact that it does not necessarily have a name.
When we call this function we use the variable name like the name of the function, as you can see in the fallowing example:
<script type="text/javascript"><!--
// Declaring a function using the function literal notation (an "anonymous" function)
var write_msg = function(msg) {
 // First we check if the argument exists
// Print a message
write_msg("Welcome!"); // Welcome!
- This script will display the message "Welcome!".

The last way to declare a function is to use the Function object constructor. The Function class has a constructor that uses the following unusual syntax:
functionName = new Function( "param1, param2,...paramX", functionBody );
- The parameter names and the "functionBody" must be written as strings.
- This will work like other functions, but the main drawback to this method is that it has poorer performance than the other methods (it is evaluated every time it is used rather than only being parsed once).
- If you were to rewrite the "write_msg()" function with this approach, it would look like this:
<script type="text/javascript"><!--
// Declaring a function using the Function class constructor
var write_msg = new Function("msg", "if (msg) document.write(msg);");
write_msg("Welcome!"); // "Welcome!"

Daily Test with Code Example

Which HTML5 tag is indicated to be used as container for menu with navigation links in Web site?
<section> <nav> <article>
 <li><a href="" title="CSS Course">CSS Course</a></li>
 <li><a href="" title="Flash Games">Flash Games</a></li>
Which CSS property shifts an item horizontally to the left or right of where it was?
text-align clear float
.some_class {
  width: 30%;
  float: left;
Click on the Math object method which returns x, rounded downwards to the nearest integer.
Math.ceil(x) Math.abs(x) Math.floor(x)
var num = 12.34567;
num = Math.floor(num);
alert(num);       // 12
Indicate the PHP function which returns the number of characters in string.
mb_strlen() count() stristr()
$str = "string with utf-8 chars åèö";
$nrchr = mb_strlen($str);
echo $nrchr;        // 30

Last accessed pages

  1. PHP PDO - exec (INSERT, UPDATE, DELETE) MySQL (41515)
  2. Add, Change, and Remove Attributes with jQuery (35983)
  3. Register and show online users and visitors (22711)
  4. Recursive function to create Multi-Level Menu in JavaScript (2753)
  5. Texarea with buttons to format text, colors and smiles (2972)

Popular pages this month

  1. Read Excel file data in PHP - PhpExcelReader (319)
  2. PhpSpreadsheet - Read, Write Excel and LibreOffice Calc files (265)
  3. Register and show online users and visitors (253)
  4. Courses Web: PHP-MySQL JavaScript Ajax HTML CSS Flash-AS3 (244)
  5. Insert, Select and Update NULL value in MySQL (156)