Subscribe:

Ads 468x60px

Monday, 3 December 2012

JavaScript: Functions


Sometimes instead of just adding your javascript to the page and having the browser perform the tasks as soon as the script is read, you might want your javascript to be performed only upon the detection of a certain event. A function is a block of code which can be called from any point in a script after it has been declared. It is basically a compartmentalized JavaScript designed to accomplish a single task. Furthermore, JavaScript written into functions will not be performed until you specifically ask for it. This way you gain complete control of the timing. Functions are useful because they contribute to rapid, reliable, error-reducing coding, and increase legibility by tiding up complicated code sequences.
A JavaScript function can take 0 or more named parameters. The function body can contain as many statements as you like, and can declare its own variables which are local to that function. The return statement can be used to return a value at any time, terminating the function. If no return statement is used (or an empty return with no value), JavaScript returns undefined.
Defining Functions
Invoking Functions
Using the Arguments array

A function definition consists of the function keyword, followed by:
  • The name of the function.
  • A list of arguments to the function, enclosed in parentheses and separated by commas.
  • The JavaScript statements that define the function, enclosed in curly braces, { }. The statements in a function can include calls to other functions defined in the current application.
  • The last statement in the statement block should be a return statement, which returns control back to whatever called the function. The keyword return can stand alone or it can be followed by a value to be returned. If no value is specified, then the function returns undefined.

0 comments:

Post a Comment