Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function can return a value.
In JavaScript, functions are first-class objects, i.e. they are objects and can be
manipulated and passed around just like any other object. Specifically, they are
Function
objects.
Every function in JavaScript is actually a Function
object. See Function
for information on properties
and methods of Function
objects.
Functions are not the same as procedures. A function always returns a value using the <u>return</u> statement, but a procedure may or may not return any value.
To return a value, the function must have a return
statement that specifies the value to return (except in the special case of a
constructor
called with the new
keyword).
A function that does not return a value returns undefined
.
The parameters of a function call are the function’s arguments. Arguments are passed to functions by value. If the function changes the value of an argument, this change is not reflected globally or in the calling function. However, object references are values, too, and they are special: if the function changes the referred object’s properties, that change is visible outside the function, as shown in the following example:
/* Declare the function 'myFunc' */
function myFunc(theObject)
{
theObject.brand = "Toyota";
}
/*
* Declare variable 'mycar';
* create and initialize a new Object;
* assign reference to it to 'mycar'
*/
var mycar = {
brand: "Honda",
model: "Accord",
year: 1998
};
/* Shows 'Honda' */
window.alert(mycar.brand);
/* Pass object reference to the function */
myFunc(mycar);
/*
* Shows 'Toyota' as the value of the 'brand' property
* of the object, as changed to by the function.
*/
window.alert(mycar.brand);
The this
keyword
does not refer to the currently executing function, so you must refer to
Function
objects by name, even within the function body. Alternatively, you can use the
arguments.callee
property which in fact is not recommended.
There are several ways to define functions:
There is a special syntax for declaring functions (see function statement for details):
function name([param[, param[, ... param]]]) {
statements
}
'name' |
The function name. |
'param' |
The name of an argument to be passed to the function. A function can have up to 255 arguments. |
'statements' |
The statements comprising the body of the function. |
A function expression is similar to and has the same syntax as a function declaration (see function operator for details):
function [name]([param] [, param] [..., param]) {
statements
}
|
The function name. Can be omitted, in which case the function becomes known as an anonymous function. |
|
The name of an argument to be passed to the function. A function can have up to 255 arguments. |
|
The statements which comprise the body of the function. |
Note
|
Arrow function expressions are an experimental technology, part of the Harmony (EcmaScript 6) proposal, and are not widely supported by browsers. |
An arrow function expression has a shorter syntax and lexically binds its this value (see <a arrow functions for details):
([param] [, param]) => {
statements
}
param => expression
param
|
The name of an argument. Zero arguments need to be indicated with |
statements or expression
|
Multiple statements need to be enclosed in brackets. A single expression requires no brackets. The expression is also the implicit return value of that function.</dd> |
As all other objects, Function
objects can be created using the new
operator:
new Function (arg1, arg2, ... argN, functionBody)
|
Zero or more names to be used by the function as formal argument names. Each must be a string that conforms to the rules for a valid JavaScript identifier or a list of such strings separated with a comma; for example “x”, “theValue”, or “a,b”. |
|
A string containing the JavaScript statements comprising the function definition. |
Invoking the Function
constructor as a function (without using the new
operator)
has the same effect as invoking it as a constructor.
Note: Using the Function
constructor to create functions is not recommended
since it needs the function body as a string which may prevent some JS engine optimizations
and can also cause other problems.
You can refer to a function’s arguments within the function by using the arguments
object.
See arguments.
<span class="comment">some section about scope and functions calling other functions</span>
A function can refer to and call itself. There are three ways for a function to refer to itself:
-
the function’s name</li>
-
an in-scope variable that refers to the function
For example, consider the following function definition:
var foo = function bar() {
// statements go here
};
Within the function body, the following are all equivalent:
-
bar()
-
arguments.callee()
-
foo()
A function that calls itself is called a recursive function. In some ways, recursion is analogous to a loop. Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case). For example, the following loop:
var x = 0;
while (x < 10) { // "x < 10" is the loop condition
// do stuff
x++;
}
can be converted into a recursive function and a call to that function:
function loop(x) {
if (x >= 10) // "x >= 10" is the exit condition (equivalent to "!(x < 10)")
return;
// do stuff
loop(x + 1); // the recursive call
}
loop(0);
However, some algorithms cannot be simple iterative loops. For example, getting all the nodes of a tree structure (e.g. the DOM) is more easily done using recursion:
function walkTree(node) {
if (node == null) //
return;
// do something with node
for (var i = 0; i < node.childNodes.length; i++) {
walkTree(node.childNodes[i]);
}
}
Compared to the function loop
, each recursive call itself makes many recursive calls here.
It is possible to convert any recursive algorithm to a non-recursive one, but often the logic is much more complex and doing so requires the use of a stack. In fact, recursion itself uses a stack: the function stack.
The stack-like behavior can be seen in the following example:
function foo(i) {
if (i < 0)
return;
document.writeln('begin:' + i);
foo(i - 1);
document.writeln('end:' + i);
}
foo(3);
which outputs:
begin:3
begin:2
begin:1
begin:0
end:0
end:1
end:2
end:3
You can nest a function within a function. The nested (inner) function is private to its containing (outer) function. It also forms a closure.
A closure is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression). |
Since a nested function is a closure, this means that a nested function can "inherit" the arguments and variables of its containing function. In other words, the inner function contains the scope of the outer function.
To summarize:
-
The inner function can be accessed only from statements in the outer function.
-
The inner function forms a closure: the inner function can use the arguments and variables of the outer function, while the outer function cannot use the arguments and variables of the inner function.
The following example shows nested functions:
function addSquares(a,b) {
function square(x) {
return x * x;
}
return square(a) + square(b);
}
a = addSquares(2,3); // returns 13
b = addSquares(3,4); // returns 25
c = addSquares(4,5); // returns 41
Since the inner function forms a closure, you can call the outer function and specify arguments for both the outer and inner function:
function outside(x) {
function inside(y) {
return x + y;
}
return inside;
}
fn_inside = outside(3);
result = fn_inside(5); // returns 8
result1 = outside(3)(5); // returns 8
Notice how x
is preserved when inside
is returned. A closure must preserve the arguments and variables in all scopes it references. Since each call provides potentially different arguments, a new closure is created for each call to outside. The memory can be freed only when the returned inside
is no longer accessible.
This is not different from storing references in other objects, but is often less obvious because one does not set the references directly and cannot inspect them.
Functions can be multiply-nested, i.e. a function (A) containing a function (B) containing a function ©. Both functions B and C form closures here, so B can access A and C can access B. In addition, since C can access B which can access A, C can also access A. Thus, the closures can contain multiple scopes; they recursively contain the scope of the functions containing it. This is called scope chaining. (Why it is called "chaining" will be explained later.)
Consider the following example:
function A(x) {
function B(y) {
function C(z) {
alert(x + y + z);
}
C(3);
}
B(2);
}
A(1); // alerts 6 (1 + 2 + 3)
In this example, C
accesses B’s `y
and A’s `x
. This can be done because:
-
B
forms a closure includingA
, i.e.B
can access `A’s arguments and variables. -
C
forms a closure includingB
.</li> -
Because
B’s closure includes `A
,C’s closure includes `A
,C
can access bothB
andA’s arguments and variables. In other words, `C
chains the scopes ofB
andA
in that order.
The reverse, however, is not true. A
cannot access C
, because A
cannot access any argument or variable of
B
, which C
is a variable of. Thus, C
remains private to only B
.
When two arguments or variables in the scopes of a closure have the same name, there is a name conflict. More inner scopes take precedence, so the inner-most scope takes the highest precedence, while the outer-most scope takes the lowest. This is the scope chain. The first on the chain is the inner-most scope, and the last is the outer-most scope. Consider the following:
function outside() {
var x = 10;
function inside(x) {
return x;
}
return inside;
}
result = outside()(20); // returns 20 instead of 10
The name conflict happens at the statement return x
and is between inside’s parameter `x
and
outside’s variable `x
. The scope chain here is {inside
, outside
, global object}.
Therefore inside’s `x
takes precedences over outside’s `x
, and 20 (inside’s `x
) is returned
instead of 10 (outside’s `x
).
Compare the following:
1) a function defined with the Function
constructor assigned to the variable multiply
var multiply = new Function("x", "y", "return x * y;");
2) a function declaration of a function named multiply
function multiply(x, y) {
return x * y;
}
3) a function expression of an anonymous function assigned to the variable multiply
var multiply = function(x, y) {
return x * y;
};
4) a function expression of a function named func_name
assigned to the variable multiply
var multiply = function func_name(x, y) {
return x * y;
};
All do approximately the same thing, with a few subtle differences:
-
There is a distinction between the function name and the variable the function is assigned to:
-
The function name cannot be changed, while the variable the function is assigned to can be reassigned.</li>
-
The function name can be used only within the function’s body. Attempting to use it outside the function’s body results in an error (or
undefined
if the function name was previously declared via avar
statement). For example:
<pre class="brush: js"> var y = function x() {}; alert(x); // throws an error </pre>
The function name also appears when the function is serialized via <a href="/en-US/docs/JavaScript/Reference/Global_Objects/Function/toString">`Function’s toString method</a>.
On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope where the function is declared in.
</li>
-
As the 4th example shows, the function name can be different from the variable the function is assigned to. They have no relation to each other.
-
A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in:
<pre class="brush: js"> function x() {} alert(x); // outputs x serialized into a string </pre>
The following example shows how function names are not related to variables functions are assigned to. If a "function variable" is assigned to another value, it will still have the same function name:
<pre class="brush: js"> function foo() {} alert(foo); // alerted string contains function name "foo" var bar = foo; alert(bar); // alerted string still contains function name "foo" </pre>
</li>
-
A function defined by '`new Function'` does not have a function name. However, in the <a href="/en-US/docs/SpiderMonkey">SpiderMonkey</a> JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example,
alert(new Function())
outputs:
<pre class="brush: js"> function anonymous() { } </pre>
Since the function actually does not have a name, anonymous
is not a variable that can be accessed within the function. For example, the following would result in an error:
<pre class="brush: js">var foo = new Function("alert(anonymous);"); foo(); </pre>
</li>
-
Unlike functions defined by function expressions or by the
Function
constructor, a function defined by a function declaration can be used before the function declaration itself. For example:
<pre class="brush: js"> foo(); // alerts FOO! function foo() { alert('FOO!'); } </pre>
</li>
-
A function defined by a function expression inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a
Function
constructor does not inherit any scope other than the global scope (which all functions inherit). -
Functions defined by function expressions and function declarations are parsed only once, while those defined by the
Function
constructor are not. That is, the function body string passed to theFunction
constructor must be parsed every time it is evaluated. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than “new Function(…)”. Therefore theFunction
constructor should be avoided whenever possible.
It should be noted, however, that function expressions and function declarations nested within the function generated by parsing aFunction constructor
's string aren’t parsed repeatedly. For example:<pre class="brush: js"> var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))(); foo(); //The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed. </pre>
</li> </ul>
A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:
-
becomes part of an expression</li>
-
is no longer a "source element" of a function or the script itself. A "source element" is a non-nested statement in the script or a function body:
var x = 0; // source element
if (x == 0) { // source element
x = 10; // not a source element
function boo() {} // not a source element
}
function foo() { // source element
var y = 20; // source element
function bar() {} // source element
while (y == 10) { // source element
function blah() {} // not a source element
y++; // not a source element
}
}
Examples:
// function declaration
function foo() {}
// function expression
(function bar() {})
// function expression
x = function hello() {}
</pre>
</li>
<li>
<pre class="brush: js">
if (x) {
// function expression
function world() {}
}
// function declaration
function a() {
// function declaration
function b() {}
if (0) {
// function expression
function c() {}
}
}
Functions can be conditionally defined using either //function statements// (an allowed extension to the
ECMA-262 Edition 3
standard) or the Function
constructor. Please note that such
function statements are no longer allowed in ES5 strict.
Additionally, this feature does not work consistently cross-browser, so you should not rely on it.
In the following script, the zero
function is never defined and cannot be invoked,
because ‘if (0)’ evaluates its condition to false:
if (0) {
function zero() {
document.writeln("This is zero.");
}
}
If the script is changed so that the condition becomes ‘if (1)’, function zero
is defined.</p>
Note: Although this kind of function looks like a function declaration, it is actually an expression (or statement), since it is nested within another statement. See differences between function declarations and function expressions.
Note: Some JavaScript engines, not including SpiderMonkey,
incorrectly treat any function expression with a name as a function definition.
This would lead to zero
being defined, even with the always-false if
condition.
A safer way to define functions conditionally is to define the function anonymously and assign it to a variable:
if (0) {
var zero = function() {
document.writeln("This is zero.");
}
}
In JavaScript, <a href="/en-US/docs/DOM">DOM</a> event handlers are functions (as opposed to objects containing a
handleEvent
method in other DOM language bindings). The functions are passed an event
object as the first and only parameter. Like any other parameter, if the event object does not need to be used,
it can be omitted in the list of formal parameters.
Possible event targets in a HTML document include:
window
(Window
objects, including frames),
document
(HTMLDocument
objects), and
elements (Element
objects).
In the HTML DOM, event targets have event handler properties.
These properties are lowercased event names prefixed with "on", e.g. onfocus
.
An alternate and more robust way of adding event listeners is provided by
DOM Level 2 Events.
Note
|
Events are part of the DOM, not of JavaScript. (JavaScript merely provides a binding to the DOM.) |
The following example assigns a function to a window’s "focus" event handler.
window.onfocus = function() {
document.body.style.backgroundColor = 'white';
};
If a function is assigned to a variable, you can assign the variable to an event handler.
The following code assigns a function to the variable setBGColor
.
var setBGColor = new Function("document.body.style.backgroundColor = 'white';");
You can use this variable to assign a function to an event handler in several ways. Here are two such ways:
-
scripting with DOM HTML event properties
document.form1.colorButton.onclick = setBGColor;
-
HTML event attribute
<input name="colorButton" type="button"
value="Change background color"
onclick="setBGColor();">
An event handler set this way is actually a function, named after the attribute, wrapped around the specified code. This is why the parenthesis in “setBGColor()” are needed here (rather than just “setBGColor”). It is equivalent to:
document.form1.colorButton.onclick = function onclick(event) {
setBGColor();
};
Note
|
the event object is passed to this function as parameter event . This allows the specified code to use the Event object:</p>
|
<input ...
onclick="alert(event.target.tagName);>
Just like any other property that refers to a function, the event handler can act as a method,
and this
would refer to the element containing the event handler.
In the following example, the function referred to by onfocus
is called with this
equal to window
.
window.onfocus();
A common JavaScript novice mistake is appending parenthesis and/or parameters to the end of the variable,
i.e. calling the event handler when assigning it. Adding those parenthesis will assign the
value returned from calling the event handler, which is often undefined
(if the function doesn’t
return anything), rather than the event handler itself:
document.form1.button1.onclick = setBGColor();
To pass parameters to an event handler, the handler must be wrapped into another function as follows:
document.form1.button1.onclick = function() {
setBGColor('some value');
};
arguments: An array-like object containing the arguments passed to the currently executing function.
<a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/callee">arguments.callee</a> <span title="This deprecated API should no longer be used, but will probably still work."><i class="icon-thumbs-down-alt"> </i></span>: Specifies the currently executing function.
<a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/caller">arguments.caller</a> <span title="This is an obsolete API and is no longer guaranteed to work."> <i class="icon-trash"> </i></span> : Specifies the function that invoked the currently executing function.
<a href="/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/length">arguments.length</a>: Specifies the number of arguments passed to the function.
The following function returns a string containing the formatted representation of a number padded with leading zeros.
// This function returns a string padded with leading zeros
function padZeros(num, totalLen) {
var numStr = num.toString(); // Initialize return value as string
var numZeros = totalLen - numStr.length; // Calculate no. of zeros
for (var i = 1; i <= numZeros; i++) {
numStr = "0" + numStr;
}
return numStr;
}
The following statements call the padZeros function.
var result;
result = padZeros(42,4); // returns "0042"
result = padZeros(42,2); // returns "42"
result = padZeros(5,4); // returns "0005"
You can determine whether a function exists by using the typeof
operator.
In the following example, a test is peformed to determine if the window
object has a
property called noFunc
that is a function. If so, it is used; otherwise some other action is taken.
if ('function' == typeof window.noFunc) {
// use noFunc()
} else {
// do something else
}
Note that in the if
test, a reference to noFunc
is used—there are no brackets "()" after the function name
so the actual function is not called.