JavaScript functions

A function is a series of commands that performs an action or computes a value. A function consists of the function name, which identifies it; parameters, which are values used by the function; and a series of commands that are run when the functions is called. Not all functions require parameters. The general syntax of a JavaScript function is:

function function_name(parameters) {
   JavaScript commands
}

Example of a function performing an action is given below. This function takes two parameters par1 and par2 and creates a table row consisting of two columns containing these parameters:

function tabRow(par1, par2) {
   document.write("<tr><td>" + par1 + </td> +
     "<td>" + par2 + "</td></tr>");
}

Try how it works:

par1:
par2:

The following function takes a number as a parameter, and computes the area of a disk of that radius. The function uses the constant PI (=3.1415...), which is a part of the Math object:

function computeArea(radius) {
   return Math.PI * radius * radius;
}

Try how it works:

radius:




The Math object offers a plenty of useful methods, some of them are listed below. Try how they work.

JavaScript codeCommentsResults
Enter x:   enter a value of x for testing
Math.abs(x) returns the absolute value of x  
Math.sin(x) returns the sine of x  
Math.cos(x) returns the cosine of x  
Math.round(x) rounds x to the nearest integer  
Math.ceil(x) rounds x up to the next highest integer  
Math.floor(x) rounds x to the next lowest integer  
Math.random() returns a random number between 0 and 1