JavaScript: Functions

Sometimes instead of just adding your javascript to the page and having the browser perform the tasks as soon as the script is read, you might want your javascript to be performed only upon the detection of a certain event. A function is a block of code which can be called from any point in a script after it has been declared. It is basically a compartmentalized JavaScript designed to accomplish a single task. Furthermore, JavaScript written into functions will not be performed until you specifically ask for it. This way you gain complete control of the timing. Functions are useful because they contribute to rapid, reliable, error-reducing coding, and increase legibility by tiding up complicated code sequences.

A JavaScript function can take 0 or more named parameters. The function body can contain as many statements as you like, and can declare its own variables which are local to that function. The return statement can be used to return a value at any time, terminating the function. If no return statement is used (or an empty return with no value), JavaScript returns undefined.

Defining functions

In JavaScript a function is defined as follows:

<script type="text/javascript">

function function_name (argument_1, ... , argument_n) 

   statement_1; 
   statement_2; 
   ...
   statement_m; 

   return return_value; 
}


</script>

A function definition consists of the function keyword, followed by:

  • The name of the function.
  • A list of arguments to the function, enclosed in parentheses and separated by commas.
  • The JavaScript statements that define the function, enclosed in curly braces, { }. The statements in a function can include calls to other functions defined in the current application. 
  • The last statement in the statement block should be a return statement, which returns control back to whatever called the function. The keyword return can stand alone or it can be followed by a value to be returned. If no value is specified, then the function returns undefined.

Have a look at the code for a function that is used to display a message. The script will not be executed before the user hits the button. We have added an onClick event to the button that will execute the function showmessage() when the button is clicked.

 
<html>
<head>

<script type="text/javascript">

function showmessage() {
   alert("WebCheatSheet - JavaScript Tutorial!");
}

</script>

</head>
<body>
<form name="myform">
<input type="button" value="Click me!" onclick="showmessage()">
</form>
</body>
</html>

Click the button to see what the script in the preceding example does:

Back to top

Invoking Functions

Defining functions doesn`t execute it. You have to call the function for it to do its work. You can invoke (or call) any function defined in the current page. You can also invoke functions defined by other named windows or frames.

You should invoke a function by name. The name needs to be followed by a set of parentheses that contain zero or more values to be passed to the function. The number of values being passed should be equal to the number of arguments the function has. The values are assigned to the arguments in the order in which they appear in the list.

For example, if you defined the example function showmessage() in the HEAD of the document, you could call it as follows:

<script type="text/javascript">
   showmessage ();
</script>

A function can even be recursive, that is, it can call itself. For example, here is a function that computes factorials:

<script type="text/javascript">

function factorial(n) {
  if ((n == 0) || (n == 1))
    return 1
   else {
      result = (n * factorial(n-1) )
      return result
   }
}

</script>

You could then display the factorials of one through 10 as follows:

 
<script type="text/javascript">

for (i = 0; i < 10; i++) {
   document.write("<BR>", i, " factorial is ", factorial(i))
}

</script>

Back to top

Using the arguments array

The arguments of a function are maintained in an array. This array contains a list of values of all arguments passed to the function. Within a function, you can address the parameters passed to it as follows:


function_name.arguments[number_of_the_argument]

The total number of arguments is indicated by the variable arguments.length.

Using the arguments array, you can call a function with more arguments than it is formally declared to accept using. This is often useful if you don’t know in advance how many arguments will be passed to the function. If you pass five arguments to a function only expecting three, only the first three will be assigned to the argument names defined with the function, but the other two are still addressable through the arguments object.

For example, consider a function defined to create HTML lists:

 
<html>
<head>
<title>WebCheatSheet - JavaScript Tutorial</title>
<script type="text/javascript">

function createList() {
   document.write("<UL>") // begin list         
   
   // iterate through arguments         
    for (var i = 0; i < createList.arguments.length; i++)                    
       document.write("<LI>" + createList.arguments[i])                    
   
    document.write("</UL>") // end list
}
</script>
</head>

<body>
<h1>WebCheatSheet - JavaScript Tutorial</h1>

<script type="text/javascript">
   createList("first","second", "third","etc");
</script>

</body>
</html>

Back to top

admin

admin

Leave a Reply

Your email address will not be published.

PHP: Functions

A function is a block of code which can be called from any point in a script after it has been declared. It is basically a compartmentalized PHP script designed to accomplish a single task. Furthermore, code contained within functions is ignored until the function is called from another part in the script. Functions are useful because they contribute to rapid, reliable, error-reducing coding, and increase legibility by tiding up complicated code sequences.

It is good programming practice to use functions to modularize your code and to better provide reuse. To declare a function, you simply type:

<?php 
   function function_name(param_1, ... , param_n)
   {
      statement_1;
      statement_2; 
      ...
      statement_m;

      return return_value;
   }
?>

We can optionally pass parameters to the functions to be known as local variable, and we can also return a result with the “return value” statement. This produces the ending of the function returning a value.

Creating a simple function

Let’s create two functions that will print the string “PHP Functions” five times, but the first one will not contain parameters, and the second one will. A function parameter is nothing more than a piece of data that the function requires to execute. In above example also included code to call the function.

<?php 
function firstFunction() 
{
    for($i = 0; $i != 5; $i++)
        echo "<P>PHP Functions!</P>";
 }

//let's add parameters to that function
function secondFunction($num, $msg) 
{
    for($i = 0; $i != $num; $i++)
        echo "<P>". $msg ."</P>";
}

echo "This is before the functions is called<br>";

echo "The first function output is:"
  firstFuction(5,"This is a function with parameters");

echo "The second function output is:";
  secondFuction(5,"This is a function with parameters");
  
echo "This is after the function has been called<br>";
?>

Next example creates a function that will calculate arithmetic mean and return a result with the “return value” statement:

<?php 
    
function aritmetic_mean($a, $b) 

   $result = ( $a + $b ) / 2; 
   return $result; 


//print the the results of calculation    
echo aritmetic_mean(4,6),"<br>"; 
echo aritmetica_mean(3242,524543),"<br>";    
?>

Variable Scope and Lifetime

It’s important to note that if you define a variable within a function, that variable is only available within that function; it cannot be referenced in another function or in the main body of your program code.  This is known as a variable’s scope.  The scope of a variable defined within a function is  local to that function.

If a function needs to use a variable that is defined in the main body of the program, it must reference it using the “global” keyword, like this:

<?php 
function AddingNumbers ( )
{
   global $sum = 2 + 2
}

$sum = 0
Addnumbers ( )
echo "2 + 2 = ".$sum
?>

While the scope of a variable defined in a function is local to that function, a variable defined in the main body of code has a global scope.  The “global” keyword tells PHP to look for a variable that has been defined outside the function.

And what about lifetime for a variable?  A variable defined within a PHP program script exists only while that script is running.  When the script ends, the variable ceases to exist.  This seems pretty obvious!  Now apply it to a function:  a variable defined within a function exists only while that function is being processed; when the function ends, the variable ceases to exist.

admin

admin

Leave a Reply

Your email address will not be published.