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

Calling Your Own Functions - Example

This section provides a quick description of how to call your own JavaScript functions and a tutorial example of calling temperature conversion function.

Once a function is defined, you can call it as part of an expression as shown in this syntax format:

   ... function_name(exp1, exp2, ...) ...;
}

When the above expression is evaluated, the following steps will be followed:

  • Step 1. The specified parameter expressions will be evaluated into primitive values or object references before passing them into the function body.
  • Step 2. The body of the specified function will be executed.
  • Step 3. The return value is collected and it will be used to evaluate the rest of the calling expression.

Here is a tutorial example that defines a simple function to convert a temperature value in Fahrenheit to Celsius:

<html>
<!-- Define_Call_Functions.html
   Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head><title>Define and Call Functions</title></head>
<body>
<pre>
<script type="text/javascript">
// Defining a new function
function f2c(fahrenheit) {
   document.write("Converting Fahrenheit = "+fahrenheit+"\n");
   var celsius = (fahrenheit - 32.0 ) / 1.8;
   document.write("Returning Celsius = "+celsius+"\n");
   return celsius;
}

// Calling the new function
   var received;
   
   document.write("\nTest 1:\n");
   received = f2c(70.0)
   document.write("Received Celsius = "+received+"\n");
   
   document.write("\nTest 2:\n");
   received = f2c(212.0)
   document.write("Received Celsius = "+received+"\n");
   
   document.write("\nTest 3:\n");
   received = f2c(0.0)
   document.write("Received Celsius = "+received+"\n");
</script>
</pre>
</body>
</html>

The output of this tutorial example shows no surprises:

Test 1:
Converting Fahrenheit = 70
Returning Celsius = 21.11111111111111
Received Celsius = 21.11111111111111

Test 2:
Converting Fahrenheit = 212
Returning Celsius = 100
Received Celsius = 100

Test 3:
Converting Fahrenheit = 0
Returning Celsius = -17.77777777777778
Received Celsius = -17.77777777777778

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
Calling Your Own Functions - Example