Begin Web Programming with PHP & MySQL

Advertisements



JavaScript Functions

A JavaScript function is a group of reusable code which can be called anywhere in the program. This eliminates the need of writing the same code again and helps programmers in writing modular codes. Functions allow a programmer to divide a big program into a number of small and manageable functions.
There are built in functions and user defined functions. Examples for built in JavaScript functions are alert(), write(), confirm() etc.

Example for a user defined function is:
<script type = "text/javascript"> function firstFunction()
{
alert("This is my first function");
}
// call firstFunction() on an event
</script>

Passing Parameters to Function

Arguments can be accessed inside functions that contain the values of the arguments (parameters) passed to that function.
Syntax:
function functionName(parameter1, parameter2, … parameter 'n')
{
code block
}

Eg:
<script>
function useArguments(fruit1, fruit2)
{
var strFruit = "Entered fruits are "+fruit1+" and "+fruit2;
document.write(strFruit);
}
useArguments("apple", "orange");
</script>

Return a Value in JavaScript Functions

The return statement stops the execution of a function and returns a value. Return statement should be the last last line in a function. We can return an array, an object literal, or a user defined object in a JavaScript function.

Eg:
<script>
function useReturns()
{
var x = 5; var y = 15;
return x + y;
}
document.write(useReturns());
</script>