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

Defining Your Own Functions - Example

This section provides a tutorial example on how to define your own JavaScript functions.

Here is a JavaScript tutorial example of defining a user function.

<html>
<!-- Define_Functions.html
   Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head><title>Define Functions</title></head>
<body>
<pre>
<script type="text/javascript">
// Defining a null function that does nothing
function null() {
}

// Defining a simple function
function hello() {
   document.write('Hello World!');
}

// Defining a function to convert Fahrenheit to Celsius
function f2c(fahrenheit) {
   document.write("Converting Fahrenheit = "+fahrenheit+"\n");
   var celsius = (fahrenheit - 32.0 ) / 1.8;
   document.write("Returning Celsius = "+celsius+"\n");
   return celsius;
}
</script>
</pre>
</body>
</html>

If you run this JavaScript page in a Web browser, you will get a blank window, because it only defines 3 functions. But it does not call any of them to run. Therefore no statement gets executed.

The first function null() is defined to do absolutely nothing.

The second function hello() is defined to write "Hello World!" into the HTML document.

The third function f2c() is defined to do a couple of things: taking a parameter "fahrenheit", declaring a local variable "celsius", assigning "celsius" with the Celsius value converted from "fahrenheit", writing two lines of text into the HTML document, returning the value in "celsius".

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 - Example