JavaScript Editor JavaScript Debugger     JavaScript Editor 

Team LiB
Previous Section Next Section


Functions are used to encapsulate code that performs a specific task. Sometimes functions are defined for commonly required tasks to avoid the repetition entailed in typing the same statements over and over. More generally, they are used to keep code that performs a particular job in one place in order to enhance reusability and program clarity.

JavaScript functions are declared with the function keyword, and the statements that carry out their operations are listed in curly braces. Function arguments are listed in parentheses following the function name and are separated by commas. For example:

function add(x, y) 
   var sum = x + y;
   return sum;

This code declares a function named add that adds its arguments together and “returns” the resulting value. The return statement tells the interpreter what value the function evaluates to. For example, you can set the value of the function equal to a variable:

var result = add(2, 3);

The arguments 2 and 3 are passed to the function, the body of the function executes, and the result of their addition, 5, is placed in the variable result.

Besides passing in literal values to a function, it is also possible to pass in variables. For example:

var a = 3, b=5;
var result;
result = add(a,b);

Experienced programmers might ask whether it is possible to modify the values of variables that are passed in to functions. The answer is more a piece of advice: no. JavaScript employs passing by value for primitive data types, so the values of the variables a and b should remain unchanged regardless of what happens in the function add. However, other data types, notably objects, can be changed when passed in (they are passed by reference), making the process confusing to some. If you have programmed in other languages before, you will recognize that functions are variously called procedures, subroutines, and methods. As you can see, functions, which are discussed in detail in Chapter 6, are very powerful.

Team LiB
Previous Section Next Section

JavaScript Editor JavaScript Debugger     JavaScript Editor