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:

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) 2013 by Dr. Herong Yang, 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

Table of Contents

 About This Book

 Introduction to JavaScript

 ECMAScript Language Specification and JavaScript Dialects

 Data Types, Variables and Expressions

 Flow Control Statements

 Creating, Accessing, and Manipulating Arrays

Defining and Calling Functions

 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

 Web Browser Supporting JavaScript

 Server-Side and Client-Side Web Scripting

 Introduction to Objects

 Defining Your Own Object Types

 Inheritance of Properties and Methods through the Prototype Object Chain

 'jrunscript' - JavaScript Shell Command from JDK

 Using Functions as "Function" Objects

 Introduction to Built-in Object Types

 W3C's Document Object Model (DOM) Specifications

 References

 PDF Printing Version