JavaScript Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 2.00

Defining Your Own Functions

This section provides a quick description of how to define your own functions and some basic features of a JavaScript function.

Like many programming languages, JavaScript allows you to define your own functions. JavaScript uses the following syntax format to define a new function:

function function_name(parameter_1, parameter_2, ...) {
   statement_1; 
   statement_2;
   ...
   return return_expression
}

There are 4 areas you need to know in order to define a new function:

  • Function Name - You should name your function so that you can call it later. "function_name" in the above syntax format.
  • Parameter List - You should name parameters of the function if you want to refer to them by names. "parameter_1", "parameter_2", ... in the above syntax format.
  • Function Body - The list of statements provided inside curly braces {} forms the function body. "statement_1", "statement_2", ... in the above syntax format.
  • Return Value - You should use "return" statements in the function body to end the execution of the function and to return a return value to the calling statement.

A JavaScript function has the following basic features:

  • Primitive parameters are passed by values.
  • Object parameters are passed by references.
  • Extra parameters can be passed into a function without list them in the function definition.
  • Parameters can be accessed through a built-in array "arguments[]" in the function body.
  • Functions can be called recursively.
  • A function provides a scope boundary for its local variables.

A tutorial example will be given in the next section showing your how to define a new function.

Sections in This Chapter

Defining Your Own Functions

Defining Your Own Functions - Example

Calling Your Own Functions - Example

Passing Parameters by Value or by Reference

Function Parameters Are Passed as Local Copies

Function Parameters Are Passed as Local Copies - Example

Global and Local Variables - Scope Rules

Global Variables - Examples

Local Variables - Examples

Collision of Global and Local Variables - Examples

"return" Statement and Return Value

Dr. Herong Yang, updated in 2008
Defining Your Own Functions