Your Search Results


    Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure—a set of statements that performs a task or calculates a value. To use a function, you must define it somewhere in the scope from which you wish to call it.

    Defining functions

    A function definition (also called a function declaration) 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 brackets, { }.

    For example, the following code defines a simple function named square:

    function square(number) {
      return number * number;

    The function square takes one argument, called number. The function consists of one statement that says to return the argument of the function (that is, number) multiplied by itself. The return statement specifies the value returned by the function.

    return number * number;

    Primitive parameters (such as a number) are passed to functions by value; the value is passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function.

    If you pass an object (i.e. a non-primitive value, such as Array or a user-defined object) as a parameter and the function changes the object's properties, that change is visible outside the function, as shown in the following example:

    function myFunc(theObject) {
      theObject.make = "Toyota";
    var mycar = {make: "Honda", model: "Accord", year: 1998},
    x = mycar.make;     // x gets the value "Honda"
    y = mycar.make;     // y gets the value "Toyota"
                        // (the make property was changed by the function)

    Note: Assigning a new object to the parameter will not have any effect outside the function, because this is changing the value of the parameter rather than the value of one of the object's properties:

    function myFunc(theObject) {
      theObject = {make: "Ford", model: "Focus", year: 2006};
    var mycar = {make: "Honda", model: "Accord", year: 1998},
    x = mycar.make;     // x gets the value "Honda"
    y = mycar.make;     // y still gets the value "Honda" 

    While the function declaration above is syntactically a statement, functions can also be created by a function expression. Such a function can be anonymous; it does not have to have a name. For example, the function square could have been defined as:

    var square = function(number) {return number * number};
    var x = square(4) //x gets the value 16

    However, a name can be provided with a function expression and can be used inside the function to refer to itself, or in a debugger to identify the function in stack traces:

    var factorial = function fac(n) {return n<2 ? 1 : n*fac(n-1)};

    Function expressions are convenient when passing a function as an argument to another function. The following example shows a map function being defined and then called with an anonymous function as its first parameter:

    function map(f,a) {
      var result = [], // Create a new Array
      for (i = 0; i != a.length; i++)
        result[i] = f(a[i]);
      return result;

    The following code:

    map(function(x) {return x * x * x}, [0, 1, 2, 5, 10]);

    returns [0, 1, 8, 125, 1000].

    In JavaScript, a function can be defined based on a condition. For example, the following function definition defines myFunc only if num equals 0:

    var myFunc;
    if (num == 0){
      myFunc = function(theObject) {
        theObject.make = "Toyota"

    In addition to defining functions as described here, you can also use the Function constructor to create functions from a string at runtime, much like eval().

    A method is a function that is a property of an object. Read more about objects and methods in Working with Objects.

    Calling functions

    Defining a function does not execute it. Defining the function simply names the function and specifies what to do when the function is called. Calling the function actually performs the specified actions with the indicated parameters. For example, if you define the function square, you could call it as follows:


    The preceding statement calls the function with an argument of 5. The function executes its statements and returns the value 25.

    Functions must be in scope when they are called, but the function declaration can be below the call, as in this example:

    /* ... */
    function square(n){return n*n} 

    The scope of a function is the function in which it is declared, or the entire program if it is declared at the top level.

    Note: This works only when defining the function using the above syntax (i.e. function funcName(){}). The code below will not work.

    square = function (n) {
      return n * n;

    The arguments of a function are not limited to strings and numbers. You can pass whole objects to a function. The show_props function (defined in Working with Objects) is an example of a function that takes an object as an argument.

    A function can call itself. For example, here is a function that computes factorials recursively:

    function factorial(n){
      if ((n == 0) || (n == 1))
        return 1;
        return (n * factorial(n - 1));

    You could then compute the factorials of one through five as follows:

    var a, b, c, d, e;
    a = factorial(1); // a gets the value 1
    b = factorial(2); // b gets the value 2
    c = factorial(3); // c gets the value 6
    d = factorial(4); // d gets the value 24
    e = factorial(5); // e gets the value 120

    There are other ways to call functions. There are often cases where a function needs to be called dynamically, or the number of arguments to a function vary, or in which the context of the function call needs to be set to a specific object determined at runtime. It turns out that functions are, themselves, objects, and these objects in turn have methods (see the Function object). One of these, the apply() method, can be used to achieve this goal.

    Function scope

    Variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function. However, a function can access all variables and functions defined inside the scope in which it is defined. In other words, a function defined in the global scope can access all variables defined in the global scope. A function defined inside another function can also access all variables defined in its parent function and any other variable to which the parent function has access.

    // The following variables are defined in the global scope
    var num1 = 20,
        num2 = 3,
        name = "Chamahk";
    // This function is defined in the global scope
    function multiply() {
      return num1 * num2;
    multiply(); // Returns 60
    // A nested function example
    function getScore () {
      var num1 = 2,
          num2 = 3;
      function add() {
        return name + " scored " + (num1 + num2);
      return add();
    getScore(); // Returns "Chamahk scored 5"

    Scope and the function stack


    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

    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)")
       // do stuff
       loop(x + 1); // the recursive call

    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) // 
       // do something with node
       for (var i = 0; i < node.childNodes.length; 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)
       document.writeln('begin:' + i);
       foo(i - 1);
       document.writeln('end:' + i);

    which outputs:


    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); // Think of it like: give me a function that adds 3 to whatever you give it
    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);
    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).


    Closures are one of the most powerful features of JavaScript. JavaScript allows for the nesting of functions and grants the inner function full access to all the variables and functions defined inside the outer function (and all other variables and functions that the outer function has access to). However, the outer function does not have access to the variables and functions defined inside the inner function. This provides a sort of security for the variables of the inner function. Also, since the inner function has access to the scope of the outer function, the variables and functions defined in the outer function will live longer than the outer function itself, if the inner function manages to survive beyond the life of the outer function. A closure is created when the inner function is somehow made available to any scope outside the outer function.

    var pet = function(name) {          // The outer function defines a variable called "name"
          var getName = function() {
            return name;                // The inner function has access to the "name" variable of the outer function
          return getName;               // Return the inner function, thereby exposing it to outer scopes
        myPet = pet("Vivie");
    myPet();                            // Returns "Vivie"

    It can be much more complex than the code above. An object containing methods for manipulating the inner variables of the outer function can be returned.

    var createPet = function(name) {
      var sex;
      return {
        setName: function(newName) {
          name = newName;
        getName: function() {
          return name;
        getSex: function() {
          return sex;
        setSex: function(newSex) {
          if(typeof newSex == "string" && (newSex.toLowerCase() == "male" || newSex.toLowerCase() == "female")) {
            sex = newSex;
    var pet = createPet("Vivie");
    pet.getName();                  // Vivie
    pet.getSex();                   // male
    pet.getName();                  // Oliver

    In the codes above, the name variable of the outer function is accessible to the inner functions, and there is no other way to access the inner variables except through the inner functions. The inner variables of the inner function act as safe stores for the inner functions. They hold "persistent", yet secure, data for the inner functions to work with. The functions do not even have to be assigned to a variable, or have a name.

    var getCode = (function(){
      var secureCode = "0]Eal(eh&2";    // A code we do not want outsiders to be able to modify...
      return function () {
        return secureCode;
    getCode();    // Returns the secureCode

    There are, however, a number of pitfalls to watch out for when using closures. If an enclosed function defines a variable with the same name as the name of a variable in the outer scope, there is no way to refer to the variable in the outer scope again.

    var createPet = function(name) {  // Outer function defines a variable called "name"
      return {
        setName: function(name) {    // Enclosed function also defines a variable called "name"
          name = name;               // ??? How do we access the "name" defined by the outer function ???

    The magical this variable is very tricky in closures. They have to be used carefully, as what this refers to depends completely on where the function was called, rather than where it was defined.

    Using the arguments object

    The arguments of a function are maintained in an array-like object. Within a function, you can address the arguments passed to it as follows:


    where i is the ordinal number of the argument, starting at zero. So, the first argument passed to a function would be arguments[0]. The total number of arguments is indicated by arguments.length.

    Using the arguments object, you can call a function with more arguments than it is formally declared to accept. This is often useful if you don't know in advance how many arguments will be passed to the function. You can use arguments.length to determine the number of arguments actually passed to the function, and then access each argument using the arguments object.

    For example, consider a function that concatenates several strings. The only formal argument for the function is a string that specifies the characters that separate the items to concatenate. The function is defined as follows:

    function myConcat(separator) {
       var result = "", // initialize list
       // iterate through arguments
       for (i = 1; i < arguments.length; i++) {
          result += arguments[i] + separator;
       return result;

    You can pass any number of arguments to this function, and it concatenates each argument into a string "list":

    // returns "red, orange, blue, "
    myConcat(", ", "red", "orange", "blue");
    // returns "elephant; giraffe; lion; cheetah; "
    myConcat("; ", "elephant", "giraffe", "lion", "cheetah");
    // returns "sage. basil. oregano. pepper. parsley. "
    myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley");

    Note: The arguments variable is "array-like", but not an array. It is array-like in that is has a numbered index and a length property. However, it does not possess all of the array-manipulation methods.

    See the Function object in the JavaScript Reference for more information.

    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() { = '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(" = '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"

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

      Note how the event object is passed to this function as parameter event. This allows the specified code to use the Event object:

      <input ...

    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.


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

    Predefined functions

    JavaScript has several top-level predefined functions:

    The following sections introduce these functions. See the JavaScript Reference for detailed information on all of these functions.

    eval Function

    The eval function evaluates a string of JavaScript code without reference to a particular object. The syntax of eval is:


    where expr is a string to be evaluated.

    If the string represents an expression, eval evaluates the expression. If the argument represents one or more JavaScript statements, eval performs the statements. The scope of eval code is identical to the scope of the calling code. Do not call eval to evaluate an arithmetic expression; JavaScript evaluates arithmetic expressions automatically.

    isFinite function

    The isFinite function evaluates an argument to determine whether it is a finite number. The syntax of isFinite is:


    where number is the number to evaluate.

    If the argument is NaN (not a number), positive infinity or negative infinity, this method returns false, otherwise it returns true.

    The following code checks client input to determine whether it is a finite number.

       /* take specific steps */

    isNaN function

    The isNaN function evaluates an argument to determine if it is "NaN." The syntax of isNaN is:


    where testValue is the value you want to evaluate.

    The parseFloat and parseInt functions return "NaN" when they evaluate a value that is not a number. isNaN returns true if passed "NaN," and false otherwise.

    The following code evaluates floatValue to determine if it is a number and then calls a procedure accordingly:

    var floatValue = parseFloat(toFloat);
    if (isNaN(floatValue)) {
    } else {

    parseInt and parseFloat functions

    The two "parse" functions, parseInt and parseFloat, return a numeric value when given a string as an argument.

    The syntax of parseFloat is:


    where parseFloat parses its argument, the string str, and attempts to return a floating-point number. If it encounters a character other than a sign (+ or -), a numeral (0-9), a decimal point, or an exponent, then it returns the value up to that point and ignores that character and all succeeding characters. If the first character cannot be converted to a number, it returns "NaN" (not a number).

    The syntax of parseInt is:

    parseInt(str [, radix]);

    parseInt parses its first argument, the string str, and attempts to return an integer of the specified radix (base), indicated by the second, optional argument, radix. For example, a radix of ten indicates to convert to a decimal number, eight octal, sixteen hexadecimal, and so on. For radixes above ten, the letters of the alphabet indicate numerals greater than nine. For example, for hexadecimal numbers (base 16), A through F are used.

    If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. If the first character cannot be converted to a number in the specified radix, it returns "NaN." The parseInt function truncates the string to integer values.

    Number and String functions

    The Number and String functions let you convert an object to a number or a string. The syntax of these functions is:

    var objRef;
    objRef = Number(objRef);
    objRef = String(objRef);

    where objRef is an object reference. Number uses the valueOf() method of the object; String uses the toString() method of the object.

    The following example converts the Date object to a readable string.

    var D = new Date(430054663215),
    x = String(D); // x equals "Thu Aug 18 04:37:43 GMT-0700 (Pacific Daylight Time) 1983"

    The following example converts the String object to Number object.

    var str = "12",
    num = Number(str);

    You can check it. Use DOM method write() and JavaScript typeof operator.

    var str = "12",
    document.write(typeof str);
    num = Number(str);
    document.write(typeof num);

    escape and unescape functions(Obsoleted above JavaScript 1.5)

    The escape and unescape functions do not work properly for non-ASCII characters and have been deprecated. In JavaScript 1.5 and later, use encodeURI, decodeURI, encodeURIComponent, and decodeURIComponent.

    The escape and unescape functions let you encode and decode strings. The escape function returns the hexadecimal encoding of an argument in the ISO Latin character set. The unescape function returns the ASCII string for the specified hexadecimal encoding value.

    The syntax of these functions is:


    These functions are used primarily with server-side JavaScript to encode and decode name/value pairs in URLs.