Functions and function scope

  • Revision slug: JavaScript/Reference/Functions_and_function_scope
  • Revision title: Functions and function scope
  • Revision id: 297254
  • Created:
  • Creator: bigbossSNK
  • Is current revision? No
  • Comment

Revision Content

Summary

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 like just like any other object. Specifically, they are Function objects.

General

Every function in JavaScript is actually a Function object. See Function for information on properties and methods of Function objects.

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.

Defining functions

There are three ways to define functions:

The function declaration (function statement)

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.

The function expression (function operator)

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
}
name
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
param
The name of an argument to be passed to the function. A function can have up to 255 arguments.
statements
The statements which comprise the body of the function.

The Function constructor

As all other objects, Function objects can be created using the new operator:

new Function (arg1, arg2, ... argN, functionBody)
arg1, arg2, ... argN
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".
functionBody
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.

The arguments object

You can refer to a function's arguments within the function by using the arguments object. See arguments.

Scope and the function stack

some section about scope and functions calling other functions

Recursion

A function can refer to and call itself. There are three ways for a function to refer to itself:

  1. the function's name
  2. arguments.callee
  3. 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:

  1. bar()
  2. arguments.callee()
  3. 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

Nested functions and closures

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

Preservation of variables

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.

Multiply-nested functions

Functions can be multiply-nested, i.e. a function (A) containing a function (B) containing a function (C). 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:

  1. B forms a closure including A, i.e. B can access A's arguments and variables.
  2. C forms a closure including B.
  3. Because B's closure includes A, C's closure includes A, C can access both B and A's arguments and variables. In other words, C chains the scopes of B and A 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.

Name conflicts

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).

Function constructor vs. function declaration vs. function expression

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.
    • 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 a var statement). For example:
      var y = function x() {};
      alert(x); // throws an error
      

      The function name also appears when the function is serialized via Function's toString method.

      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.

    • 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:
    function x() {}
    alert(x); // outputs x serialized into a string
    

    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:

    function foo() {}
    alert(foo); // alerted string contains function name "foo"
    var bar = foo;
    alert(bar); // alerted string still contains function name "foo"
    
  • A function defined by 'new Function' does not have a function name. However, in the SpiderMonkey JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, alert(new Function()) outputs:
    function anonymous() {
    }
    

    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:

    var foo = new Function("alert(anonymous);");
    foo();
    
  • 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:
    foo(); // alerts FOO!
    function foo() {
       alert('FOO!');
    }
    
  • 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 the Function 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 the Function constructor should be avoided whenever possible.
    It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a Function constructor 's string aren't parsed repeatedly. For example:
    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.

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
  • 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() {}
    
  • if (x) {
       // function expression
       function world() {}
    }
    
  • // function declaration
    function a() {
       // function declaration
       function b() {}
       if (0) {
          // function expression
          function c() {}
       }
    }
    

Conditionally defining a function

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.

Note: Although this kind of function looks like a function declaration, it is actually a 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.");
   }
}

Functions as event handlers

In JavaScript, DOM 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:

  1. scripting with DOM HTML event properties
    document.form1.colorButton.onclick = setBGColor;
    
  2. 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 how the event object is passed to this function as parameter event. This allows the specified code to use the Event object:

    <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');
};

Local variables within functions

arguments: An array-like object containing the arguments passed to the currently executing function.

arguments.callee {{ Deprecated_inline() }}: Specifies the currently executing function.

arguments.caller {{ Obsolete_inline() }} : Specifies the function that invoked the currently executing function.

arguments.length: Specifies the number of arguments passed to the function.

Examples

Example: Returning a formatted number

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" 

Example: Determining whether a function exists

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.

See also

{{ languages( {"zh-cn":"zh-cn/JavaScript/Reference/Functions+and+function+scope", "es": "es/Referencia_de_JavaScript_1.5/Funciones", "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Fonctions", "ja": "ja/JavaScript/Reference/Functions_and_function_scope", "ru": "ru/\u042f\u0434\u0440\u043e_JavaScript_1.5_\u0421\u043f\u0440\u043e\u0432\u0447\u043d\u0438\u043a/Functions" } ) }}

Revision Source

<h2 id="Summary" name="Summary" style="position: static; z-index: auto; ">Summary</h2>
<p>Generally speaking, a function is a "subprogram" that can be <em>called</em> 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 <em>function body</em>. Values can be <em>passed</em> to a function, and the function can <em>return</em> a value.</p>
<p>In JavaScript, functions are first-class objects, i.e. they are objects and can be manipulated and passed around like just like any other object. Specifically, they are <code><a href="/en/JavaScript/Reference/Global_Objects/Function" title="en/Core_JavaScript_1.5_Reference/Global_Objects/Function">Function</a></code> objects.</p>
<h2 id="General" name="General">General</h2>
<p>Every function in JavaScript is actually a <code>Function</code> object. See <code><a href="/en/JavaScript/Reference/Global_Objects/Function" title="en/Core_JavaScript_1.5_Reference/Global_Objects/Function">Function</a></code> for information on properties and methods of <code>Function</code> objects.</p>
<p>To return a value, the function must have a <code><a href="/en/JavaScript/Reference/Statements/return" title="en/Core_JavaScript_1.5_Reference/Statements/return">return</a></code> statement that specifies the value to return (except in the special case of a <a href="/en/JavaScript/Reference/Global_Objects/Object/constructor" title="constructor">constructor</a> called with the <code><a href="/en/JavaScript/Reference/Operators/new" title="new">new</a></code> keyword). A function that does not return a value returns <code>undefined</code>.</p>
<p>The parameters of a function call are the function's <em>arguments</em>. Arguments are passed to functions <em>by value</em>.&nbsp; 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:</p>
<pre class="brush: js">
 /* Declare the function 'myFunc' */
 function myFunc(theObject)
 {
   theObject.brand = "Toyota";
 }
 
 /*
  *&nbsp;Declare variable 'mycar';
  *&nbsp;create and initialize a new Object;
  *&nbsp;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.
  */
&nbsp;window.alert(mycar.brand);
</pre>
<p>The <a href="/en/JavaScript/Reference/Operators/this" title="this"><code>this</code> keyword</a> does not refer to the currently executing function, so you must refer to <code>Function</code> objects by name, even within the function body. Alternatively, you can use the <a href="/en/JavaScript/Reference/Functions_and_function_scope/arguments/callee" title="En/Core_JavaScript_1.5_Reference/Functions_and_function_scope/arguments/callee">arguments.callee</a> property which in fact is not recommended.</p>
<h2 id="Defining_functions" name="Defining_functions">Defining functions</h2>
<p>There are three ways to define functions:</p>
<h3 id="The_function_declaration_.28function_statement.29" name="The_function_declaration_.28function_statement.29">The function declaration (<code>function</code> statement)</h3>
<p>There is a special syntax for declaring functions (see <a href="/en/JavaScript/Reference/Statements/function" title="en/Core_JavaScript_1.5_Reference/Statements/function">function statement</a> for details):</p>
<pre class="eval">
function <em>name</em>([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) {
   <em>statements</em>
}
</pre>
<dl>
  <dt>
    <code>name</code></dt>
  <dd>
    The function name.</dd>
</dl>
<dl>
  <dt>
    <code>param</code></dt>
  <dd>
    The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd>
</dl>
<dl>
  <dt>
    <code>statements</code></dt>
  <dd>
    The statements comprising the body of the function.</dd>
</dl>
<h3 id="The_function_expression_.28function_operator.29" name="The_function_expression_.28function_operator.29">The function expression (<code>function</code> operator)</h3>
<p>A function expression is similar to and has the same syntax as a function declaration (see <a href="/en/JavaScript/Reference/Operators/function" title="en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/function_Operator">function operator</a> for details):</p>
<pre class="eval">
function [<em>name</em>]([<em>param</em>] [, <em>param</em>] [..., <em>param</em>]) {
   <em>statements</em>
}
</pre>
<dl>
  <dt>
    <code>name</code></dt>
  <dd>
    The function name. Can be omitted, in which case the function becomes known as an anonymous function.</dd>
</dl>
<dl>
  <dt>
    <code>param</code></dt>
  <dd>
    The name of an argument to be passed to the function. A function can have up to 255 arguments.</dd>
</dl>
<dl>
  <dt>
    <code>statements</code></dt>
  <dd>
    The statements which comprise the body of the function.</dd>
</dl>
<h3 id="The_Function_constructor" name="The_Function_constructor">The <code>Function</code> constructor</h3>
<p>As all other objects, <code><a href="/en/JavaScript/Reference/Global_Objects/Function" title="en/JavaScript/Reference/Global_Objects/Function">Function</a></code> objects can be created using the <code>new</code> operator:</p>
<pre class="eval">
new Function (<em>arg1</em>, <em>arg2</em>, ... <em>argN</em>, <em>functionBody</em>)
</pre>
<dl>
  <dt>
    <code>arg1, arg2, ... arg<em>N</em></code></dt>
  <dd>
    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 "<code>x</code>", "<code>theValue</code>", or "<code>a,b</code>".</dd>
</dl>
<dl>
  <dt>
    <code>functionBody</code></dt>
  <dd>
    A string containing the JavaScript statements comprising the function definition.</dd>
</dl>
<p>Invoking the <code>Function</code> constructor as a function (without using the <code>new</code> operator) has the same effect as invoking it as a constructor.</p>
<div class="note">
  <strong>Note:</strong> Using the <code>Function</code> 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.</div>
<h2 id="The_arguments_object" name="The_arguments_object">The <code>arguments</code> object</h2>
<p>You can refer to a function's arguments within the function by using the <code>arguments</code> object. See <a href="/en/JavaScript/Reference/Functions_and_function_scope/arguments" title="En/Core_JavaScript_1.5_Reference/Functions_and_function_scope/arguments">arguments</a>.</p>
<h2 id="Scope_and_the_function_stack" name="Scope_and_the_function_stack">Scope and the function stack</h2>
<p><span class="comment">some section about scope and functions calling other functions</span></p>
<h2 id="Recursion" name="Recursion">Recursion</h2>
<p>A function can refer to and call itself. There are three ways for a function to refer to itself:</p>
<ol>
  <li>the function's name</li>
  <li><code><a href="/en/JavaScript/Reference/Functions_and_function_scope/arguments/callee" title="En/Core_JavaScript_1.5_Reference/Functions_and_function_scope/arguments/callee">arguments.callee</a></code></li>
  <li>an in-scope variable that refers to the function</li>
</ol>
<p>For example, consider the following function definition:</p>
<pre class="brush: js">
var foo = function bar() {
   // statements go here
};
</pre>
<p>Within the function body, the following are all equivalent:</p>
<ol>
  <li><code>bar()</code></li>
  <li><code>arguments.callee()</code></li>
  <li><code>foo()</code></li>
</ol>
<p>A function that calls itself is called a <em>recursive function</em>. 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:</p>
<pre class="brush: js">
var x = 0;
while (x &lt; 10) { // "x &lt; 10" is the loop condition
   // do stuff
   x++;
}
</pre>
<p>can be converted into a recursive function and a call to that function:</p>
<pre class="brush: js">
function loop(x) {
   if (x &gt;= 10) // "x &gt;= 10" is the exit condition (equivalent to "!(x &lt; 10)")
      return;
   // do stuff
   loop(x + 1); // the recursive call
}
loop(0);
</pre>
<p>However, some algorithms cannot be simple iterative loops. For example, getting all the nodes of a tree structure (e.g. the <a href="/en/DOM" title="en/DOM">DOM</a>) is more easily done using recursion:</p>
<pre class="brush: js">
function walkTree(node) {
   if (node == null) // 
      return;
   // do something with node
   for (var i = 0; i &lt; node.childNodes.length; i++) {
      walkTree(node.childNodes[i]);
   }
}
</pre>
<p>Compared to the function <code>loop</code>, each recursive call itself makes many recursive calls here.</p>
<p>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.</p>
<p>The stack-like behavior can be seen in the following example:</p>
<pre class="brush: js">
function foo(i) {
   if (i &lt; 0)
      return;
   document.writeln('begin:' + i);
   foo(i - 1);
   document.writeln('end:' + i);
}
foo(3);
</pre>
<p>which outputs:</p>
<pre class="eval">
begin:3
begin:2
begin:1
begin:0
end:0
end:1
end:2
end:3
</pre>
<h2 id="Nested_functions_and_closures" name="Nested_functions_and_closures">Nested functions and closures</h2>
<p>You can nest a function within a function. The nested (inner) function is private to its containing (outer) function. It also forms a <em>closure</em>.</p>
<dl>
  <dd>
    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).</dd>
</dl>
<p>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.</p>
<p>To summarize:</p>
<ul>
  <li>The inner function can be accessed only from statements in the outer function.</li>
</ul>
<ul>
  <li>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.</li>
</ul>
<p>The following example shows nested functions:</p>
<pre class="brush: js">
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
</pre>
<p>Since the inner function forms a closure, you can call the outer function and specify arguments for both the outer and inner function:</p>
<pre class="brush: js">
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
</pre>
<h3 id="Efficiency_considerations" name="Efficiency_considerations" style="position: static; z-index: auto; ">Preservation of variables</h3>
<p>Notice how <code>x</code> is preserved when <code>inside</code> 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 <code>inside</code> is no longer accessible.</p>
<p>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.</p>
<h3 id="Multiply-nested_functions" name="Multiply-nested_functions">Multiply-nested functions</h3>
<p>Functions can be multiply-nested, i.e. a function (A) containing a function (B) containing a function (C). 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 <em>scope chaining</em>. (Why it is called "chaining" will be explained later.)</p>
<p>Consider the following example:</p>
<pre class="brush: js">
function A(x) {
   function B(y) {
      function C(z) {
         alert(x + y + z);
      }
      C(3);
   }
   B(2);
}
A(1); // alerts 6 (1 + 2 + 3)
</pre>
<p>In this example, <code>C</code> accesses <code>B</code>'s <code>y</code> and <code>A</code>'s <code>x</code>. This can be done because:</p>
<ol>
  <li><code>B</code> forms a closure including <code>A</code>, i.e. <code>B</code> can access <code>A</code>'s arguments and variables.</li>
  <li><code>C</code> forms a closure including <code>B</code>.</li>
  <li>Because <code>B</code>'s closure includes <code>A</code>, <code>C</code>'s closure includes <code>A</code>, <code>C</code> can access both <code>B</code> <em>and</em> <code>A</code>'s arguments and variables. In other words, <code>C</code> <em>chains</em> the scopes of <code>B</code> and <code>A</code> in that order.</li>
</ol>
<p>The reverse, however, is not true. <code>A</code> cannot access <code>C</code>, because <code>A</code> cannot access any argument or variable of <code>B</code>, which <code>C</code> is a variable of. Thus, <code>C</code> remains private to only <code>B</code>.</p>
<h3 id="Name_conflicts" name="Name_conflicts">Name conflicts</h3>
<p>When two arguments or variables in the scopes of a closure have the same name, there is a <em>name conflict</em>. 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:</p>
<pre class="brush: js">
function outside() {
   var x = 10;
   function inside(x) {
      return x;
   }
   return inside;
}
result = outside()(20); // returns 20 instead of 10
</pre>
<p>The name conflict happens at the statement <code>return x</code> and is between <code>inside</code>'s parameter <code>x</code> and <code>outside</code>'s variable <code>x</code>. The scope chain here is {<code>inside</code>, <code>outside</code>, global object}. Therefore <code>inside</code>'s <code>x</code> takes precedences over <code>outside</code>'s <code>x</code>, and 20 (<code>inside</code>'s <code>x</code>) is returned instead of 10 (<code>outside</code>'s <code>x</code>).</p>
<h2 id="Function_constructor_vs._function_declaration_vs._function_expression" name="Function_constructor_vs._function_declaration_vs._function_expression"><code>Function</code> constructor vs. function declaration vs. function expression</h2>
<p>Compare the following:</p>
<ol>
  <li>a function defined with the <code>Function</code> constructor assigned to the variable <code>multiply</code>
    <pre class="brush: js">
var multiply = new Function("x", "y", "return x * y;");
</pre>
  </li>
  <li>a <em>function declaration</em> of a function named <code>multiply</code>
    <pre class="brush: js">
function multiply(x, y) {
   return x * y;
}
</pre>
  </li>
  <li>a <em>function expression</em> of an anonymous function assigned to the variable <code>multiply</code>
    <pre class="brush: js">
var multiply = function(x, y) {
   return x * y;
};
</pre>
  </li>
  <li>a <em>function expression</em> of a function named <code>func_name</code> assigned to the variable <code>multiply</code>
    <pre class="brush: js">
var multiply = function func_name(x, y) {
   return x * y;
};
</pre>
  </li>
</ol>
<p>All do approximately the same thing, with a few subtle differences:</p>
<ul>
  <li>There is a distinction between the function name and the variable the function is assigned to:
    <ul>
      <li>The function name cannot be changed, while the variable the function is assigned to can be reassigned.</li>
      <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 <code>undefined</code> if the function name was previously declared via a <code>var</code> statement). For example:
        <pre class="brush: js">
var y = function x() {};
alert(x); // throws an error
</pre>
        <p>The function name also appears when the function is serialized via <a href="/en/JavaScript/Reference/Global_Objects/Function/toString" title="en/Core_JavaScript_1.5_Reference/Global_Objects/Function/toString"><code>Function</code>'s toString method</a>.</p>
        <p>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.</p>
      </li>
      <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.</li>
    </ul>
  </li>
  <li>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>
    <p>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:</p>
    <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>
  <li>A function defined by '<code>new</code>&nbsp;<code>Function'</code> does not have a function name. However, in the <a href="/en/SpiderMonkey" title="en/SpiderMonkey">SpiderMonkey</a> JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, <code>alert(new Function())</code> outputs:
    <pre class="brush: js">
function anonymous() {
}
</pre>
    <p>Since the function actually does not have a name, <code>anonymous</code> is not a variable that can be accessed within the function. For example, the following would result in an error:</p>
    <pre class="brush: js">
var foo = new Function("alert(anonymous);");
foo();
</pre>
  </li>
  <li>Unlike functions defined by function expressions or by the <code>Function</code> 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>
  <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 <code>Function</code> constructor does not inherit any scope other than the global scope (which all functions inherit).</li>
  <li>Functions defined by function expressions and function declarations are parsed only once, while those defined by the <code>Function</code> constructor are not. That is, the function body string passed to the <code>Function</code> 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 "<code>new Function(...)</code>". Therefore the <code>Function</code> constructor should be avoided whenever possible.<br />
    It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a <code>Function constructor</code> '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>
<p>A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:</p>
<ul>
  <li>becomes part of an expression</li>
  <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:
    <pre class="brush: js">
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
   }
}
</pre>
  </li>
</ul>
<p>Examples:</p>
<ul>
  <li>
    <pre class="brush: js">
// 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() {}
}
</pre>
  </li>
  <li>
    <pre class="brush: js">
// function declaration
function a() {
   // function declaration
   function b() {}
   if (0) {
      // function expression
      function c() {}
   }
}
</pre>
  </li>
</ul>
<h3 id="Conditionally_defining_a_function" name="Conditionally_defining_a_function">Conditionally defining a function</h3>
<p>Functions can be conditionally defined using either //function statements// (an allowed extension to the <a class="external" href="http://www.ecma-international.org/publications/standards/Ecma-262.htm">ECMA-262 Edition 3</a> standard) or the <code>Function</code> constructor. Please note that such <a class="link-https" href="https://bugzilla.mozilla.org/show_bug.cgi?id=609832" title="https://bugzilla.mozilla.org/show_bug.cgi?id=609832">function statements are no longer allowed in ES5 strict</a>. Additionally, this feature does not work consistently cross-browser, so you should not rely on it.</p>
<p>In the following script, the <code>zero</code> function is never defined and cannot be invoked, because '<code>if (0)</code>' evaluates its condition to false:</p>
<pre class="brush: js">
if (0) {
   function zero() {
      document.writeln("This is zero.");
   }
}
</pre>
<p>If the script is changed so that the condition becomes '<code>if (1)</code>', function <code>zero</code> is defined.</p>
<p>Note: Although this kind of function looks like a function declaration, it is actually a statement, since it is nested within another statement. See <a href="#Function_constructor_vs._function_declaration_vs._function_expression">differences between function declarations and function expressions</a>.</p>
<p>Note: Some JavaScript engines, not including <a href="/en/SpiderMonkey" title="en/SpiderMonkey">SpiderMonkey</a>, incorrectly treat any function expression with a name as a function definition. This would lead to <code>zero</code> being defined, even with the always-false <code>if</code> condition. A safer way to define functions conditionally is to define the function anonymously and assign it to a variable:</p>
<pre class="brush: js">
if (0) {
   var zero = function() {
      document.writeln("This is zero.");
   }
}
</pre>
<h2 id="Functions_as_event_handlers" name="Functions_as_event_handlers">Functions as event handlers</h2>
<p>In JavaScript, <a href="/en/DOM" title="en/DOM">DOM</a> event handlers are functions (as opposed to objects containing a <code>handleEvent</code> method in other DOM language bindings). The functions are passed an <a href="/en/DOM/event" title="en/DOM/event">event</a> 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.</p>
<p>Possible event targets in a <a href="/en/HTML" title="en/HTML">HTML</a> document include: <code>window</code> (<code>Window</code> objects, including frames), <code>document</code> (<code>HTMLDocument</code> objects), and elements (<code>Element</code> objects). In the <a class="external" href="http://www.w3.org/TR/DOM-Level-2-HTML/">HTML DOM</a>, event targets have event handler properties. These properties are lowercased event names prefixed with "on", e.g. <code>onfocus</code>. An alternate and more robust way of adding event listeners is provided by <a class="external" href="http://www.w3.org/TR/DOM-Level-2-Events/">DOM Level 2 Events</a>.</p>
<p>Note: Events are part of the DOM, not of JavaScript. (JavaScript merely provides a binding to the DOM.)</p>
<p>The following example assigns a function to a window's "focus" event handler.</p>
<pre class="brush: js">
window.onfocus = function() {
   document.body.style.backgroundColor = 'white';
};
</pre>
<p>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 <code>setBGColor</code>.</p>
<pre class="brush: js">
var setBGColor = new Function("document.body.style.backgroundColor = 'white';");
</pre>
<p>You can use this variable to assign a function to an event handler in several ways. Here are two such ways:</p>
<ol>
  <li>scripting with DOM HTML event properties
    <pre class="brush: js">
document.form1.colorButton.onclick = setBGColor;
</pre>
  </li>
  <li>HTML event attribute
    <pre class="brush: html">
&lt;input name="colorButton" type="button"
   value="Change background color"
   onclick="setBGColor();"/&gt;
</pre>
    <p>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 "<code>setBGColor()</code>" are needed here (rather than just "<code>setBGColor</code>"). It is equivalent to:</p>
    <pre class="brush: js">
document.form1.colorButton.onclick = function onclick(event) {
   setBGColor();
};
</pre>
    <p>Note how the event object is passed to this function as parameter <code>event</code>. This allows the specified code to use the Event object:</p>
    <pre class="brush: html">
&lt;input ...
    onclick="alert(event.target.tagName);"/&gt;
</pre>
  </li>
</ol>
<p>Just like any other property that refers to a function, the event handler can act as a method, and <code>this</code> would refer to the element containing the event handler. In the following example, the function referred to by <code>onfocus</code> is called with <code>this</code> equal to <code>window</code>.</p>
<pre class="brush: js">
window.onfocus();
</pre>
<p>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 <em>value returned from calling the event handler</em>, which is often <code>undefined</code> (if the function doesn't return anything), rather than the event handler itself:</p>
<pre class="brush: js">
document.form1.button1.onclick = setBGColor();
</pre>
<p>To pass parameters to an event handler, the handler must be wrapped into another function as follows:</p>
<pre class="brush: js">
document.form1.button1.onclick = function() {
   setBGColor('some value');
};
</pre>
<h2 id="Local_variables_within_functions" name="Local_variables_within_functions">Local variables within functions</h2>
<p><a href="/en/JavaScript/Reference/Functions_and_function_scope/arguments" title="En/Core_JavaScript_1.5_Reference/Functions_and_function_scope/arguments">arguments</a>: An array-like object containing the arguments passed to the currently executing function.</p>
<p><a href="/en/JavaScript/Reference/Functions_and_function_scope/arguments/callee" title="En/Core_JavaScript_1.5_Reference/Functions_and_function_scope/arguments/callee">arguments.callee</a> {{ Deprecated_inline() }}: Specifies the currently executing function.</p>
<p><a href="/en/JavaScript/Reference/Functions_and_function_scope/arguments/caller" title="En/Core_JavaScript_1.5_Reference/Functions_and_function_scope/arguments/caller">arguments.caller</a> {{ Obsolete_inline() }}&nbsp;: Specifies the function that invoked the currently executing function.</p>
<p><a href="/en/JavaScript/Reference/Functions_and_function_scope/arguments/length" title="En/Core_JavaScript_1.5_Reference/Functions_and_function_scope/arguments/length">arguments.length</a>: Specifies the number of arguments passed to the function.</p>
<h2 id="Examples" name="Examples">Examples</h2>
<h3 id="Example:_Returning_a_formatted_number" name="Example:_Returning_a_formatted_number">Example: Returning a formatted number</h3>
<p>The following function returns a string containing the formatted representation of a number padded with leading zeros.</p>
<pre class="brush: js">
// 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 &lt;= numZeros; i++) {
      numStr = "0" + numStr;
   }
   return numStr;
}
</pre>
<p>The following statements call the padZeros function.</p>
<pre class="brush: js">
var result;
result = padZeros(42,4); // returns "0042"
result = padZeros(42,2); // returns "42"
result = padZeros(5,4);  // returns "0005" 
</pre>
<h3 id="Example:_Determining_whether_a_function_exists" name="Example:_Determining_whether_a_function_exists">Example: Determining whether a function exists</h3>
<p>You can determine whether a function exists by using the <code>typeof</code> operator. In the following example, a test is peformed to determine if the <code>window</code> object has a property called <code>noFunc</code> that is a function. If so, it is used; otherwise some other action is taken.</p>
<pre class="brush: js">
 if ('function' == typeof window.noFunc) {
   // use noFunc()
 } else {
   // do something else
 }
</pre>
<p>Note that in the <code>if</code> test, a reference to <code>noFunc</code> is used—there are no brackets "()" after the function name so the actual function is not called.</p>
<h2 id="See_also" name="See_also">See also</h2>
<ul>
  <li><code><a href="/en/JavaScript/Reference/Global_Objects/Function" title="en/Core_JavaScript_1.5_Reference/Global_Objects/Function">Function</a></code></li>
  <li><a href="/en/JavaScript/Reference/Statements/function" title="en/Core_JavaScript_1.5_Reference/Statements/function"><code>function</code> statement</a></li>
  <li><a href="/en/JavaScript/Reference/Operators/function" title="en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/function_Operator"><code>function</code> operator</a></li>
</ul>
<p>{{ languages( {"zh-cn":"zh-cn/JavaScript/Reference/Functions+and+function+scope", "es": "es/Referencia_de_JavaScript_1.5/Funciones", "fr": "fr/R\u00e9f\u00e9rence_de_JavaScript_1.5_Core/Fonctions", "ja": "ja/JavaScript/Reference/Functions_and_function_scope", "ru": "ru/\u042f\u0434\u0440\u043e_JavaScript_1.5_\u0421\u043f\u0440\u043e\u0432\u0447\u043d\u0438\u043a/Functions" } ) }}</p>
Revert to this revision