HTML and CSS Reference
In-Depth Information
Dealing with functions
In JavaScript, a function is a bit of code bundled up into a block and optionally given a name. If a function
is not given a name, it is called an anonymous function. Functions represent a scope and are treated like
objects; they may have properties and can be passed around as arguments and interacted with.
You use functions for two main reasons: for defining repeatable behavior, and for creating custom
Named functions for repeatable behavior
A named (as opposed to anonymous ) function is defined as follows:
function doSomeCalculation(number) {
return number;
Defined in this way, the function is globally visible and is interpreted as a new member added to
the JavaScript global object. You can call the function from anywhere in your code, as shown below:
var result = doSomeCalculation(3);
JavaScript functions can be called with any number of arguments—regardless of the declared
number of parameters. In other words, you may have a function like doSomeCalculation, which
declares just one argument (number) , but you can invoke it by passing any (greater) number of
var result = doSomeCalculation(1, 2);
Although browsers may tolerate this type of coding, it is still a bad programming practice.
However, you can leverage such flexibility to easily define functions that deliberately accept a variable
number of arguments.
In JavaScript, a function can access declared parameters by name or by position using a predefined
array called arguments . This array returns the actual list of parameters passed to the function. In this
way, for example, the function below can accept any number of arguments and process them.
function doSum() {
var result = 0;
for(var i=0; i<arguments.length; i++)
result += arguments[i];
return result;
Search WWH ::

Custom Search