4 Sept 2013

Functions

   Functions

         learn-design-development-javascriptFunctions help organize the various parts of a script into different tasks that must be accomplished.
A function contains code that will be executed by an event or by a call to the function.
Functions can be used more than once within a script to perform their task. Rather than rewriting the entire block of code, you can simply call the function again.
There are two kinds of functions:
  • predefined - for example: "parseInt(string)", "parseFloat(string)", ...
  • Created by developer
    • - that returns a value
    • - not return a value

                  Declaring Functions

Functions can be defined both in the and in the section of a document. However, to assure that a function is read/loaded by the browser before it is called, it's better to put functions in the section.
The most basic way to define a function is using the word "function", the name of the function followed by two parentheses (where we can add the parameters) and a pair of cfurly brackets that contain the code of the function.
Function syntax
function functionName(var1, var2, ...) {
  code to be executed
}
The parameters var1, var2, etc. are variables or values passed into the function. The brackets { and the } defines the start and end of the function.
- A function with no parameters must include the parentheses () after the function name.

Function names are case sensitive, be sure you use the identical name when you call the function.
The word function must be written in lowercase letters.

  • The Return Statement

return statement is used to specific a value that a function returns to the main script. You place the return statement as the last line of the function before the closing curly bracket and end it with a semicolon.
For example, to return the value of a variable "some_var", the return statement looks like this:
                return some_var; The next function returns the value of a variable 'z' that contain the amount of two parameers (x, y):

function amount(x, y) {
  var z = x+y;
  return z;
}
- The "amount" is the name of the function, "x" and "y" are the parametres. The function returns the value of "z" variable, that contain the amount of "x" and "y".

  • Calling Functions

After the function is defined, we can call and use it.
You may call a function from anywhere within a page (or even from other pages if the function is embedded in an external .js file). You can even call a function inside of another function.
A function with parameters can be called using the syntax:

functionName(arg1, arg2, ...);
- "arg1", "arg2", ... are the arguments passed to the function.
A function without paramentre with the following syntax:

functionName();
Note that the function call no longer use the word "function" and braces
In the place of the script where we call a function it's e
xecuted the code of that function.

No comments:

Post a Comment