HTML and CSS Reference
In-Depth Information
Function Arguments
JavaScript does not check that the arguments passed to a function match the signature of the
function. For instance:
• You can pass more arguments to a function than it expects; in this case the extra arguments
will be ignored.
• You can pass fewer arguments to a function than it expects; in this case the arguments are
assigned the value of undefined .
A side effect of this is that it is not possible to overload functions or methods
in JavaScript. In many languages it is possible to define multiple versions of the
same function, but with different parameter lists (or signatures). The compiler
then determines the correct version to invoke based on the parameters provided.
In order to achieve this in JavaScript the functions must be given different names,
otherwise JavaScript cannot determine the correct version to invoke.
There are legitimate reasons to pass fewer arguments to a function than it expects. You may
be happy for these arguments to be undefined .
There are also legitimate reasons to pass more arguments to a function than its signature spe-
cifies. For instance, consider a function that accepts an arbitrary number of arguments, and
adds them all together.
Any time a function is invoked a variable called arguments is available inside the function.
This is an array containing all the variables passed to the function. This means we can
defined an add function as a function that accepts no parameters, but instead uses the argu-
ments array:
> function add() {
var result = 0;
for (var i = 0; i < arguments.length; i++) {
result += arguments[i];
return result;
Search WWH ::

Custom Search