JavaScript Tutorials - Herong's Tutorial Examples - 2.33, by Herong Yang
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) 2002 HerongYang.com. All Rights Reserved. --> <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".
Table of Contents
ECMAScript Language Specification and JavaScript Dialects
Data Types, Variables and Expressions
Creating, Accessing, and Manipulating Arrays
►Defining and Calling 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
Collision of Global and Local Variables - Examples
"return" Statement and Return Value
Web Browser Supporting JavaScript
Server-Side and Client-Side Web Scripting
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