A function is a group of steps that perform a task, or multiple tasks, or calculates a value for use in the program. Here are some examples of what a function might do:

  • make things happen when the visitor clicks on a button
  • calculate the cost of an item after a discount is applied
  • verify that a form was filled out correctly

In JavaScript a function might run the moment the browser window is open. It may run when the user clicks on a button or submits a form. The function may get called from onother function.

If you have a series of steps that will need to be run from various places on the page, you can save a great deal of coding by just having the one function set up and it is called from other functions.


How to define a function in JavaScript

You define a function (or declare a function) with the following:

  • the word function
  • its name
  • a set of parentheses
  • possibly some arguments contained in these parentheses
  • a list of statements to perform contained in curly brackets

Here are some simple functions:

function goRed(){
    document.getElementsByTagName("body").style.background = "red";

function calcNum(x, y) {
    var finalNum = x * y;

In the first example, no arguments are being passed to the function. In the second example, the arguments are x and y. These arguments are values that are required for the function to run.


What are the arguments passed to a function in JavaScript?

Arguments are bits of information that are handed over to the function so it can do its work.

An example would be that you have a form that the visitor fills out. On that form you put the amount of a loan and how long the term is. The JavaScript program will gather this information and pass it to the function as the arguments.

function calcPayment(loanAmt, loanTerm){
    var payment = /* math goes here  */ ;

These arguments can be a single value or an array with many values.


How to call a function in JavaScript

A function will just sit inside your <script> tags and do nothing until you call it into action. Just because you defined the function in the program, does not mean that it will be executed.

You must call the function to set it into motion.

For example, you have the function calcPayment(loanAmt, loanTerm){...} defined in your program. You need to call this from elsewhere in your program where you got that information.

var loanAmt = form.loanAmt.value;
var loanTerm = form.loanTerm.value;
var payment = calcPayment(loanAmt, loanTerm);

In the example above, not only did you set the function into motion, you also got the value that the function returns. If set up with a return(); line, the function will send back a piece of information that you need to proceed with the program.