JavaScript Functions
A function is a group of reusable code which can be called anywhere in your
program. This eliminates the need of writing same code again and again. This
will help programmers to write modular code. You can divide your big program in
a number of small and manageable functions.
Like any other advance programming language, JavaScript also supports all
the features necessary to write modular code using functions.
JavaScript allows us to write our own functions as well. This section will
explain you how to write your own functions in JavaScript.
Function Definition:
Before we use a function we need to define that function. The most common
way to define a function in JavaScript is by using the function keyword,
followed by a unique function name, a list of parameters (that might be empty),
and a statement block surrounded by curly braces. The basic syntax is shown
here:
<script type="text/JavaScript">
function functionname(parameter-list)
{ statements } </script>
|
Calling a Function:
To invoke a function somewhere later in the script, you would simple need to
write the name of that function as follows:
<script type="text/JavaScript">
functionname();
</script>
|
Function Parameters:
There is a facility to pass different parameters while calling a function.
These passed parameters can be captured inside the function and any
manipulation can be done over those parameters.
A function can take multiple parameters separated by comma.
Example:
Let us do a bit modification in our
sayHello function. This time it
will take two parameters:
<script type="text/JavaScript">
function sayHello(name, age)
{
alert (name + “is” + age + “years old.");
}
</script>
|
Note: We are using
+ operator to concatenate string and number
all together. JavaScript does not mind in adding numbers into strings.
Now we can call this function as follows:
<script type="text/JavaScript">
sayHello('Zara', 7 );
</script>
|
The return Statement:
A JavaScript function can have an optional
return statement. This is
required if you want to return a value from a function. This statement should
be the last statement in a function.
Example:
This function takes two parameters and concatenates them and return
resultant in the calling program:
<script type="text/JavaScript">
<!--
function concatenate(first, last)
{
var full;
full = first + last;
return full;
}
//-->
</script>
|
Now we can call this function as follows:
<script type="text/JavaScript">
<!--
var result;
result = concatenate('Zara', 'Ali');
alert(result );
//-->
</script>
|
No comments:
Post a Comment