JavaScript: The Definitive Guide

Previous Chapter 3
Variables and Data Types
Next
 

3.5 Functions

A function is a piece of JavaScript code that is defined once in a program and can be executed, or invoked, many times by the program. JavaScript functions can be passed arguments or parameters that specify the value or values that the function is to operate upon, and can return values. Functions are defined in JavaScript with code like the following:

function square(x)
{
  return x*x;
}

Once a function is defined, you can invoke it by following the function's name with a comma-separated list of arguments within parentheses. The following lines are function invocations:

y = square(x);
compute_distance(x1, y1, z1, x2, y2, z2)
click()
y = sin(x);

An unusual feature of JavaScript is that functions are actual data types. In many languages, including Java, functions are a syntactic feature of the language, and can be defined and invoked, but they are not data types. The fact that functions are true data types in JavaScript gives a lot of flexibility to the language. It means that functions can be stored in variables, arrays, and objects, and it means that functions can be passed as arguments to other functions. This can quite often be useful. We'll learn more about defining and invoking functions, and also about using them as data values, in Chapter 6, Functions.

Since functions are data types just like numbers, and strings, they can be assigned to object properties just like other values can. When a function is assigned to a property of an object (described below), it is often referred to as a method of that object. Some special methods of certain objects are automatically invoked by the web browser when the user interacts with the browser (by clicking the mouse, for example). These special methods are called event handlers. We'll see more about methods in Chapter 7, Objects, and about event handlers in Chapter 10, Client-Side Program Structure.


Previous Home Next
boolean Values Book Index Objects

HTML: The Definitive Guide CGI Programming JavaScript: The Definitive Guide Programming Perl WebMaster in a Nutshell