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".