Tuesday, March 18, 2014

JavaScript Functions

A function is a group of reusable code which can be called anywhere in your programme. This eliminates the need of writing same code again and again. This will help programmers to write modular code. You can divide your big programme 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.
You must have seen functions like alert() and write() in previous chapters. We are using these function again and again but they have been written in core JavaScript only once.
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>

Example:

A simple function that takes no parameters called sayHello is defined here:
<script type="text/javascript">
<!--
function sayHello()
{
   alert("Hello there");
}
//-->
</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">
<!--
sayHello();
//-->
</script>

Function Parameters:

Till now we have seen function without a parameters. But 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.
For example you can pass two numbers in a function and then you can expect from the function to return their multiplication in your calling program.

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>

Advanced Concepts for Functions:

There is lot to learn about JavaScript functions. But I have put following important concepts in this tutorial. If you are not in furry then I would suggest to go through them at least once.

  • JavaScript Nested Functions

    Prior to JavaScript 1.2, function definition was allowed only in toplevel global code but JavaScript 1.2 allows function definitions to be nested within other functions as well.
    Still there is a restriction that function definitions may not appear within loops or conditionals. These restrictions on function definitions apply only to function declarations with the function statement.
    As we'll discuss later in next chapter, function literals (another feature introduced in JavaScript 1.2) may appear within any JavaScript expression, which means that they can appear within if and other statements.

    Example:

    Following is the example where we have nested two functions. This may be a bit confusing but it works perfectly fine:
    <script type="text/javascript">
    <!--
    function hypotenuse(a, b) {
       function square(x) { return x*x; }
       
       return Math.sqrt(square(a) + square(b));
    }
    //-->
    </script>
    
    Note: Here we are using a function sqrt from Math class. We will see it when we will discuss about Objects.
    Now you can call this function in usual way as follows:
    <script type="text/javascript">
    <!--
    hypotenuse(1, 2);  // This will produce 2.2360
    //-->
    </script> 
     
  • JavaScript Function( ) Constructor

    The function statement is not the only way to define a new function but also, you can define your function dynamically using Function( ) constructor along with the new operator.
    Note: This is the terminology from Object Oriented Programming. You may not feel comfortable for the first time, which is OK.

    Syntax:

    Following is the syntax to create a function using Function( ) constructor along with the new operator.
    <script type="text/javascript">
    <!--
    var variablename = new Function(Arg1, Arg2..., "Function Body");
    //-->
    </script>
    
    The Function() constructor expects any number of string arguments. The last argument is the body of the function - it can contain arbitrary JavaScript statements, separated from each other by semicolons.
    Notice that the Function() constructor is not passed any argument that specifies a name for the function it creates. The unnamed functions created with the Function() constructor are called anonymous functions.

    Example:

    Here is an example of creating a function in this way:
    <script type="text/javascript">
    <!--
    var func = new Function("x", "y", "return x*y;");
    //-->
    </script>
    
    This line of code creates a new function that is more or less equivalent to a function defined with the familiar syntax:
    <script type="text/javascript">
    <!--
    function f(x, y){ 
       return x*y; 
    }
    //-->
    </script>
    
    It means you can call above function as follows:
    <script type="text/javascript">
    <!--
    func(10,20); // This will produce 200
    //-->
    </script> 
     
  • JavaScript Function Literals
    JavaScript 1.2 introduces the concept of function literals which is one more new way of defining functions.
    A function literal is an expression that defines an unnamed function.

    Syntax:

    The syntax for a function literal is much like that of the function statement, except that it is used as an expression rather than as a statement and no function name is required.
    <script type="text/javascript">
    <!--
    var variablename = function(Argument List){
                           Function Body 
                       };
    //-->
    </script>
    
    Syntactically, you can specify a function name while creating a literal function as follows:
    <script type="text/javascript">
    <!--
    var variablename = function FunctionName(Argument List){ 
                          Function Body 
                       };
    //-->
    </script>
    
    But this name does not have any significance, so worth not to use it.

    Example:

    Here is an example of creating a function in this way:
    <script type="text/javascript">
    <!--
    var func = function(x,y){ return x*y };
    //-->
    </script>
    
    You can call above function as follows:
    <script type="text/javascript">
    <!--
    func(10,20); // This will produce 200
    //-->
    </script>
    

No comments:

Post a Comment