Professional Documents
Culture Documents
Types of Functions
o Pre-defined Functions
o User-defined Functions
Function names can contain letters, digits, underscores, and dollar signs
(same rules as variables).
Before using a function or we can say before calling a function in our program
we have to define its definition in between the curly braces. As per your
requirement, we can leave the parameter list blank as you can see in the syntax
given above.
Example
<script types="text/javascript">
<!--
function Hello(){
alert("Hi, there");
}
//-->
</script>
How to call the function
We can call the function when we want to use the function in the program by
writing its name as you can see below:
Hello();
Let's see a program in which, we will create a function and use it in the
program.
<html>
<head>
<title>Functions!!!</title>
<script type="text/javascript">
function myfirstFunction()
{
document.write("This is just a simple user-defined function.<br />");
}
myfirstFunction();
</script>
</head>
<body>
</body>
</html>
To call the function somewhere else in the script, we just have to write its name
as you can see in the given example:
Example
<html>
<head>
<script type = "text/javascript">
functionsayhi() {
document.write ("Hello there!");
}
</script>
</head>
<body>
<p>Click the given button to call the function</p>
<form>
<input type = "button" onclick = "sayhi()" value = "Say Hello">
</form>
</body>
</html>
Function With Parameters
function functionname( parameter1,parameter2,....parameterN)
{
Lines of code to be executed/set of instructions to be executed in order to per
form a specific task.
}
We can understand how to use parameters with function more easily with the
help of an example:
<html>
<head>
<script type = "text/javascript">
Function sayHello(name, age,gender) {
document.write (name + " is " + age + " years old" + " and gender is " + gender);
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "sayHello(' Isabella', 23,'female')" value = "Say H
ello">
</form>
</body>
</html>
In this program, we created a function named "sayHello ()" with three parameters:
name, age, and gender, and defined it in the head section of the HTML document. To
use this function, we also created a button using the form tag in the program's body
section and pass the values as arguments. When the user clicks that button, our
function is called and gets executed.
Function functionname(arg1, arg2)
{
//Set of instructions to be executed
return val1;
}