What's a Javascript Function?
A function is a piece of code that sits dormant until it is referenced or called upon to do its "function". In addition to controllable execution,Javascript functions are also a great time saver for doing repeatable tasks.
Instead of having to type out the code every time you want something done, you can simply call the Javascript function multiple times to get the same effect. This benefit is also known as "code reusability".
How to Define a Javascript Function
The syntax for creating a function is:
function functionname(var1,var2,...,varX)
{
some code
}
var1, var2, etc are variables or values passed into the Javascript function. The { and the } defines the start and end of the Javascript function.
Note: A Javascript function with no parameters must include the parentheses () after the function name:
function functionname()
{
some code
}
Note: Do not forget about the importance of capitals in JavaScript! The word function must be written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a function with the exact same capitals as in the function name.
--------------------------------------------------------------------------------
The return Statement
The return statement is used to specify the value that is returned from the function.
So, functions that are going to return a value must use the return statement.
Example
The Javascript function below should return the product of two numbers (a and b):
function prod(a,b)
{
x=a*b
return x
}
When you call the function above, you must pass along two parameters:
product=prod(2,3)
The returned value from the prod() function is 6, and it will be stored in the variable called product.
|