01/10/2014

JavaScript Functions

A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it.
Example:
<script>
function myFunction(a, b) {
return a * b;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>
JavaScript Function Syntax
A JavaScript function is defined with the function keyword, followed by aname, followed by parentheses ().
Function names can contain letters, digits, underscores, and dollar signs same rules as variables.
The parentheses may include parameter names separated by commas:(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {} function Name (parameter1, parameter2, parameter3) { code to be executed }
Function parameters are the names listed in the function definition.
Function arguments are the real values received by the function when it is invoked. Inside the function, the arguments are used as local variables. A Function is much the same as a Procedure or a Subroutine, in other programming languages. Function Invocation The code inside the function will execute when something invokes the function:
*When an event occurs when a user clicks a button
*When it is invoked called from JavaScript code
*Automatically self invoked
Function Return
When JavaScript reaches are turn statement, the function will stop executing. If the function was invoked from a statement, JavaScript will return to execute the code after the invoking statement.
Functions often compute are turn value. The return value is returned back to the caller:
Example:
Calculate the product of two numbers, and return the result:
<script>
function myFunction(a, b) {
return a * b;
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>
Why Functions?
You can reuse code:
Define the code once, and use it many times. You can use the same code many times with different arguments, to produce different results.
Example:
Convert Fahrenheit to Celsius:
<script>
function toCelcius(f)
{
return (5/9) * (f-32);
}
document.getElementById("demo").innerHTML = toCelcius(32);
</script>
JavaScript Functions are Objects
In JavaScript, functions are objects. JavaScript functions have properties and methods. You can add your own properties and methods to functions.
JavaScript Functions are Variables Too
In JavaScript, functions can be used as variables:
Example:
<script> document.getElementById("demo").innerHTML = "The temperature is " + toCelsius(32) + " Centigrade"; function toCelsius(fahrenheit) { 牋  return (5/9) * (fahrenheit-32); } </script>
JavaScript functions can be redefined like ordinary variables.
JavaScript functions can also be passed as values to other functions.