Try my app Expense Manager @ google play and amazon store.

Friday, June 22, 2012

Java Script Tutorial 15 : JavaScript Functions


Function :
A function is a block of code that executes only when you tell it to execute. It can be when an event occurs, like when a user clicks a button, or from a call within your script, or from a call within another function. Functions can be placed both in the <head> and in the <body> section of a document, just make sure that the function exists, when the call is made. Syntax to write a function is as follows :


function functionname()
{
     some code
}


The word function must be written in lowercase letters. Example of JavaScript function is below.


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function myfunc()
{
     alert("Called by JS Function!");
}
</script>
</head>
<body>
<button onclick="myfunc()">Click Me !</button>
</body>
</html>


Function with Arguments :
When you call a function, you can pass along some values to it, these values are called arguments or parameters. These arguments can be used inside the function. You can send as many arguments as you like, separated by commas (,). Declare the argument, as variables, when you declare the function. Syntax to write function with arguments is as follow :


function myfunc(var1,var2)
{
      some code here.
}


For example


<script type="text/javascript">
function myFunction(var1,var2)
{
alert("you passed " + var1 + ", and " + var2);
}
</script>
<button onclick="myfunc('isb','pak')">Click Me !</button>


Functions With a Return Value :
Sometimes you want your function to return a value back to where the call was made. This is possible by using the return statement. When using the return statement, the function will stop executing, and return the specified value. Syntax of function with return value is as follow :


function myfunc()
{
     var y=10;
     var z=5;
     return y+z;
}


The function above will return the value 15. The function-call will be replaced with the returnvalue. For example


var x=myfunc();


After executing function "myfunc", value of x will be 15. The return value of function can be directly written into html elements. For example


document.getElementById("id").innerHTML=myfunc();


The return statement is also used when you simply want to exit a function.

No comments:

Post a Comment

Follow by Email

Google+ Badge