Web Hosting Offers
See the new scripts recently added to Dynamic Drive. Click here.
Original, practical CSS codes and examples such as CSS menus for your site.
javascript tutorial Browse Advanced JavaScript Tutorial
Browse JavaScript Script resources
Browse JavaScript FAQS
JavaScript Tutorial: Browse
javascript tutorial
Buy templates
Home >> Tutorials >> Basic Javascript Tutorials

Javascript Functions:
 
Defining function Calling function

Functions are one of the very important features in JavaScript. A Function is a set of JavaScript statements kept together. Before you call  a function, you must first define it. When you call a function, you execute the javascript statements in that function. You can pass values or parameters also to a function.


Javascript - Defining functions

Generally, functions are defined between  the <HEAD> and </HEAD> tags of a HTML file. This makes sure that all functions are defined before any content is displayed. You can also place all of your functions into a separate file, and include them in a page using the SRC attribute of the SCRIPT tag.

A function definition has :

  • The function keyword
  • A function name
  • A comma-separated list of arguments to the function in parentheses
  • Statements in the functioning curly braces

  •  

     
     
     

    General Format:
    function Name(arguments)
    {
    statement1;
    statement2;
    .
    .
    .
    statementn;
    }
     

    A function need not have  arguments.

    Eg.1 A function without parameters

    function TestFunction1() {
      document.write("I am a function. I have no parameters :(");
    }

    Eg2: A function With parameters

    function TestFunction2(name,address) {
      document.write("I am a function. I have 2 parameters !");
    alert('Name: ' + name + ', Address:' + address);
    }

    Top




    Javascript - Calling functions

     You call a function simply by specifying its name followed by a parenthetical list of arguments, if any:

    eg1
    TestFunction1()

    eg2:

    TestFunction1('tom','mytown, New York,NY')

    Example:

    <html>
    <script language="JavaScript">
    <!-- hide

    function TestFunction1() {
        document.write("I am a function. I have no parameters :(");
    }

    function TestFunction2(name,address) {
        document.write("I am a function. I have 2 parameters !");
        document.write('Name: ' + name + ', Address:' + address);
    }

    // Call TestFunction1
    TestFunction1();

    // Call TestFunction2
    TestFunction2('tom','mytown, New York,NY')
    // -->
    </script>
    </html>

    Output:

    I am a function. I have no parameters :(
    I am a function. I have 2 parameters !
    Name: Tom, Address: mytown, New York,NY

    Top



     
     
     

    Page contents: itechies.net - Learn how to create a function in Javascript
    javascript tutorial
    javascript book
    Buy this book