/

HTML / CSS / JavaScript Tutorial

JavaScript Tutorial

4. Functions

[this page | pdf | back links]

A JavaScript function is a block of JavaScript code that can be executed as a discrete unit. It involves a function statement along the lines of e.g.:

 

               function func() {

document.getElementById("element").innerHTML = "Hello";

}

 

Function definitions can include parameters (separated by a comma if more than one parameter), e.g. the following (if passed a string variable) would allow any text to be inserted in the relevant element’s innerHTML.

 

               function func2(x) {

document.getElementById("element").innerHTML = x;

}

 

Such a function would be invoked by JavaScript such as func2("Hello World").

 

Functions are much like procedures or subroutines in other programming languages. The code inside the curly brackets executes when the function is invoked. This can happen when an event occurs, when the function is called from JavaScript code or sometimes when it is self-invoked. If a function includes a return statement then the function will stop executing and will return the value identified by the function’s return statement. The function (technically, a special type of object) can be distinguished from the act of invoking it.  The () operator invokes the function, e.g. in the above func refers to the function object, but func() will invoke the function itself.

 

The function parameters are the names listed in the function definition (i.e. the x in the definition of func2). Function arguments are the values received by the function (i.e. assigned to the function parameters) when it is invoked.

 

Function names can contain letters, digits, underscores and dollar signs (the same rules as apply to variable naming applies to function naming). Wherever a variable can be used, a valid function call evaluating to the same value can also be used.

 


NAVIGATION LINKS
Contents | Prev | Next | JavaScript


Desktop view | Switch to Mobile