So what is a function?
functions is a block of code that perform a routine or process. it can return a value or not return anything at all, just execute a block of code. It can also accept arguments or parameters. A function must not be duplicated in a document(which may contain more that 1 javascript). However it can be called many times.
Here's some example of the syntax, foo can be anything provided it doesnt begin with number and only contains letter and underscore.
function that execute a code
function foo() {
alert("hi");
}
how to call:
foo();
will show an alert with "hi" message
function that execute a code but requires a parameter
function foo(message) {
alert(message);
}
how to call:
foo("hi");
will show an alert with "hi" message
function returns a value
function foo() {
return "hi";
}
how to call:
alert(foo());
will show an alert with "hi" message
function returns a value but requires a parameter
function foo(message) {
if(message) return true;
return false;
}
how to call:
will show an alert with "true" messagealert(foo("hi"));
so now you know how to use a function. As I said a function must not be duplicated, it will cause bugs if you do.
Why use functions?
Basically we want our code short, in practicality we use function so that we can execute the same code many times without making the same code.








No comments:
Post a Comment