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 :

 


 

 

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

Leave a Comment