Basics
Creating a Document
Head and Body Elements
Formatting Text
Creating Lists
Embedding Images
URLs Explained
Linking to Documents
Creating Tables
Forms Form Basics
Input and Textarea
Select Lists
Frames Framesets
The Frame Element
Nested Framesets
Targetting Frames
Inline Frames
Tips and Tricks Meta Tags
Transition Effects
HTML Generators Create a Document
Create a List
Create a Table
HTML
Basics
Implementing CSS
CSS Syntax
Pseudo Classes/Elements
CSS Classes
CSS Properties Font Properties
Color and Background
Text Properties
Border Properties
Margins and Padding
Size and Position
Tips and Tricks Menu Buttons
Special Effects
CSS
Basics
Running a Script
Variables
Expressions and Operators
Objects.Properties.Methods
The Date Object
Strings
Regular Expressions
Defining RegExp Patterns
Branches and Conditions
Loops
Arrays Array Basics
Array Methods
Sorting Arrays

User-Defined Functions
Cookies
Windows
Frames
Tips and Tricks Image Replacement
Using Includes
Form Validation
Debugging
JavaScript
Basics
Creating a Script
Running a Script
Variables
Expressions and Operators
Strings Strings Basics
Strings and Substrings
Replacing Substrings
Regular Expressions
Branches and Conditions
Loops
Arrays Array Basics
Array Functions
Sorting Arrays
User-Defined Functions
Include and Require
Uploading Files
File Functions
Session Variables
Tips and Tricks Page Templates
Form Reply Scripts
Form Validation
JavaScript to PHP
PHP
Basics
Create and Drop
Show and Describe
Insert, Update and Delete
Querying
Join Queries
Functions
Table Locking
PHP/MySQL Functions Accessing a Database
Querying with PHP
Create and Drop with PHP
Insert and Update with PHP
Frequently Used Functions MySQL
Basics
Layout and Navigation
Page Content Style
Web Page Copy
Graphics and Animation
HTML Forms
Accessibility
Legal Requirements
MySQL
JavaScriptBasicsRunning a ScriptVariablesExpressions and OperatorsObjects.Properties.MethodsThe Date ObjectStringsRegular ExpressionsDefining RegExp PatternsBranches and ConditionsLoopsArraysArray MethodsSorting ArraysJavaScript User-Defined FunctionsUser-Defined FunctionsCookiesWindowsFrames

Home > JavaScript > User-Defined Functionsprinter version

User-Defined Functions

As well as library functions, JavaScript allows you to create your own functions.

Functions provide a way to group JavaScript statements into blocks that are reusable - making for more compact code and easier maintenance.

Functions are first defined then called from within the script in the same way as library functions. Functions can be defined anywhere within a script but it's normal to define them at the start.

A function may have no arguments (sometimes called parameters) or it may have many. A Function may also return arguments.

Defining a Function



Example of a function() Definition
<script language="javascript" type="text/javascript">
    function highlight (text)
    {
        text = "<b><i>"+text.toUpperCase()+"</i></b>";
        document.write(text);
    }

    this_string = "warning";

    // This prints out WARNING in bold italic
    highlight (this_string);
</script>


JavaScript makes no check on the data types passed as arguments to a function so it's up to the programmer to ensure that they match - if that's important.

Also no check is made on the number of arguments passed. If less are passed than required then the missing ones will be considered undefined. Excess arguments are just ignored.

Returning Values

A function can use the return statement to pass back values as in the example below.

Example of Returning a Value
<script language="javascript" type="text/javascript">
    function add (number_1, number_2)
    {
        result = number_1 + number_2;
        return (result);
    }

    // This prints out 8
    document.write (add (5, 3));
</script>


Variable Scope

When a variable is created, its value is not automatically available at every point in the programme.

There is a relationship between where it is created and where it can be used. This relationship is called the variable's scope.

When a variable is created inside a function it is a local variable and only has scope inside the function. It only exists when the function is called and is discarded when the function ends.

An Example of Scope
<script language="javascript" type="text/javascript">
    function showscope ()
    {
        var variablescope = "Local";
        document.write (variablescope);
    }

    var variablescope = "Global";

    // This prints out Local as you'd expect
    showscope ();

    /* This prints out Global because variablescope created
    inside the function is different to variablescope
    outside the function */
    document.write (variablescope);
</script>


The same is true for function arguments. They are local and only have scope within the function.

Another Example of Scope
<script language="javascript" type="text/javascript">
    function showscope (variablescope)
    {
        variablescope = "Local";
        document.write (variablescope);
    }

    var variablescope = "Global";

    // This prints out Local as you'd expect
    showscope (variablescope);

    /* This prints out Global because the function
    was only passed a copy of variablescope so variablescope
    has not been changed by the function */
    document.write (variablescope);
</script>


If a variable is passed to a function or created inside a function then even if it has the same name as a variable outside the function it isn't the same variable.

Global Variables

A variable inside a function with the same name as a variable outside the function IS global if it has neither been created (i.e. declared) inside the function nor passed to the function.

Example of Global Scope
<script language="javascript" type="text/javascript">
    function showscope ()
    {
        variablescope = "Local";
        document.write (variablescope);
    }

    var variablescope = "Global";

    // This prints out Local as you'd expect
    showscope ();

    /* This also prints out Local because the function wasn't passed
     a copy of variablescope nor was variablescope created inside
     the function so variablescope has been changed */
    document.write (variablescope);
</script>


This is a good reason for always properly declaring variables using the var keyword when you create them.

If you don't stick to this habit you may end up with bugs that can be very difficult to trace.

Note: When you give a function the right to alter a global variable you pass a lot of power to the function so you should only do so when absolutely necessary.

If lots of functions are allowed to alter a global variable in a large programme, it can be very difficult to remember which functions are changing the variable.


The Function() Constructor

As well as using the function keyword to create a function, you can also use the Function() constructor along with the new operator.

This does essentially the same thing but with a couple of differences.

  1. A function can be created dynamically depending on set conditions. This means however that the function has to be compiled each time it's called - instead of just once.
  2. The function can be defined as part of an expression instead of as a statement.


The Function() constructor takes any number of string arguments. The last string argument is made up of the JavaScript statements, separated with semicolons, that will form the body of the function.

Any string arguments before the last string argument are treated as the names of the arguments that the function will use.

The Function() constructor does not require the name of the function as an argument since the function is defined like a variable and given a name.

Example of Using the Function() Constructor
<script language="javascript" type="text/javascript">
    var add = new Function ("number_1", "number_2", "result = number_1 + number_2;return (result);");

    // This prints out 8
    document.write (add (5, 3));
</script>


Using Functions as Data

When a function is given a name it can be thought of as a variable that holds the function.

And in the same way that a variable may be set to equal another variable then a function may be assigned to another variable.

Example of a Function as Data
<script language="javascript" type="text/javascript">
    function add (number_1, number_2)
    {
        result = number_1 + number_2;
        return (result);
    }

    // Assign function add() to variable compute
    var compute = add(5, 3);

    // This prints out 8
    document.write (compute);
</script>


Functions may also be assigned to object properties and when they are they are known as methods (covered in the Objects.Properties.Methods Tutorial).

Example of Creating a Method
<script language="javascript" type="text/javascript">
    // Create an object called numbers
    var numbers = new Object();

    // Add a method called add to the object
    numbers.add = new Function ("number_1", "number_2", "result = number_1 + number_2;return (result);");

    // Assign the object to a variable called sum
    var sum = numbers.add (5, 3);

    // This prints out 8
    document.write (sum);
</script>


Previous - JavaScript Sorting Arrays Previous - Sorting Arrays     Next - Cookies Next - JavaScript Cookies


Privacy | Terms | Contact | Links | Sitemap | RSS Feeds RSS and JavaScript Feeds
©2010 www.webdesignworkmate.co.uk all rights reserved 
Design and Production by smallbizonline website design © 2000-2010
Valid HTML 4.01! Level Double-A conformance icon, W3C-WAI Web Content Accessibility Guidelines 1.0Valid CSS!
Tips and TricksImage ReplacementUsing IncludesForm ValidationDebugging
Got any JavaScript Tips?
Send me your tip and if it's suitable I'll put it on the site, credit it to you and add a link back to your site.
Recommended Reading
Javascript the definitive guide

Javascript and DHTML cookbook

Pro javascript techniques

simply javascript