You are here: Reference > JavaScript > core > objects > Function

Function object

Browser support:
Represents a function in JavaScript.
Functions are reusable code snippets that can be used as many times as you wish, like in any other language.

The Function object inherits from the Function.prototype object, and the Function.prototype object inherits from the Object.prototype object. The Object.prototype object is the base object for all JavaScript objects. The Function object inherits all of its properties and methods from the Function.prototype and the Object.prototype objects, except the prototype property that refers to the Function.prototype object. Objects that can be instantiated inherit from the Function.prototype, the others inherit from the Object.prototype object.

Syntax:

Creating a Function object:
var funcName = new Function ([arg1[, arg2[, ... argN]],] functionBody)
arg1[, arg2[, ... argN] Optional. Strings that specifies the name of the parameters.
functionBody Optional. String that specifies the code that will be executed when the function is called. If any string value is specified in the constructor of the Function object, the last string value is always the functionBody parameter.
Creating a Function object with function literal:
function funcName ([arg1[, arg2[, ... argN]]) {
    functionBody
}

or

var funcName = function ([arg1[, arg2[, ... argN]]) {
    functionBody
}
arg1[, arg2[, ... argN] Optional. The parameters of the function.
functionBody Optional. Block of code that will be executed when the function is called.

Function operations

Creating a simple function:
function Multiply (x, y) {
    return (x * y);
}
Did you find this example helpful? yes no
The Multiply function multiplies two values.
var Multiply = new Function ("x", "y", "return (x * y);");
Did you find this example helpful? yes no
The Multiply function in this example is equivalent to the previous one.
How to call a function:
function Multiply (x, y) {
    return (x * y);
}

    // call Multiply
var mul = Multiply (2, 3);
    // output 6
document.write (mul);
Did you find this example helpful? yes no
Recursive functions:
function Factorial (n) {
    if (n <= 1) {
        return 1;
    }
    return n * Factorial (n-1);
}

var fact = Factorial (4);
    // output 24
document.write (fact);
Did you find this example helpful? yes no
The Factorial function returns the factorial of an integer.
A function with a variable-length argument list:
function Add () {
    var sum = 0;
    for (var i = 0; i < arguments.length; i++) {
        sum += arguments[i];
    }
    return sum;
}

var n = Add (2, 3);
document.write (n);  // 5

document.write ("<br />");

n = Add (1, 2, 3, 4, 5);
document.write (n);  // 15
Did you find this example helpful? yes no
The Add method uses the arguments object that contains information about the parameters specified by the caller.
Nested functions:
    // The AddReciprocals function adds the two given number exponentials and returns the result.
function AddReciprocals (a, b) {
        // The GetReciprocal function can be called from the AddReciprocals function only.
    function GetReciprocal (x) {
        return (1 / x);
    }
    return (GetReciprocal (a) + GetReciprocal (b));
}

var exp1 = AddReciprocals (1, 2);  // returns 1.5
document.write (exp1);

document.write ("<br />");

var exp2 = AddReciprocals (2, 4);  // returns 0.75
document.write (exp2);
Did you find this example helpful? yes no
Nested functions are only exists within the scope of a specific function, they cannot be called directly from outside.
Functions are also objects:
function Rectangle (a, b){
    this.a = a;
    this.b = b;
}

var rect = new Rectangle (2, 3);

document.write (rect.a);    // 2
document.write ("<br />");
document.write (rect.b);    // 3
Did you find this example helpful? yes no
Creating member functions:
Not recommended solution:
function Rectangle (a, b){
    this.a = a;
    this.b = b;
    this.Area = function () {
        return this.a * this.b;
    }
}

var rect = new Rectangle (2, 3);
document.write (rect.Area ());  // 6
Did you find this example helpful? yes no
Recommended solution:
function Rectangle (a, b){
    this.a = a;
    this.b = b;
}

Rectangle.prototype.Area = function () {
    return this.a * this.b;
};

var rect = new Rectangle (2, 3);
document.write (rect.Area ());  // 6
Did you find this example helpful? yes no
In case of the first solution, each instance of the Rectangle object has its own copy of the Area method. It is inefficient, because extra memory is allocated for each instance.
The second solution is better. In that case, the Area method exists in only one instance and it is shared amongst all the instances of the Rectangle object.

Members:

The Function object inherited from the Function.prototype and Object.prototype objects. The following lists only contain the members of the Function and Function.prototype objects.

Properties:

Property Support Description
arguments*
Deprecated, use the global arguments object instead. Refers to an object that contains information about the parameters specified by the caller. The number of the parameters specified by the caller can be different from the number of parameters declared for the current function (length property). With the use of the arguments object, functions with variable-length parameter list can be implemented. See the page for the arguments object and Example 1 and 2 below for further details.
arity*
Returns the number of parameters declared for the current function. Deprecated, use the cross-browser length property instead.
caller*
Returns the function that executed the current function, if any.
constructor*
Returns a reference to the constructor function that created the current object.
length*
Returns the number of parameters declared for the current function. If you need the number of the parameters specified by the caller, use the arguments object. See Example 1 for further details.
name*
10.5
Returns the name of the current function.
prototype
Returns a reference to the Function.prototype object. The Function.prototype object allows adding properties and methods to the Function object that can be used with instances of the Function object, like any predefined property or method. The prototype property is static, it cannot be accessed from an instance of the Function object, only Function.prototype is allowed.

(*) - The property is inherited from the Function.prototype.

Methods:

Method Support Description
apply ([thisObj [,argArray]])*
Executes a method of an object in the context of another object. Typically used for variable-length argument lists and object inheritance. The apply and call methods are similar, the only difference is that the apply method passes the parameters as an array. See Example 3, 4, and 5 for further details.
thisObj Optional. The object to use as this in the called method. If this parameter is not specified or null, this refers to the window object.
argArray Optional. Specifies the array of arguments.
call (thisObj [, arg1 [, arg2 [, ...]]])*
Executes a method of an object in the context of another object. Typically used for object inheritance. The apply and call methods are similar, the only difference is that the apply method passes the parameters as an array. See Example 3, 4, and 5 for further details.
thisObj Optional. The object to use as this in the called method. If this parameter is not specified or null, this refers to the window object.
arg1 [, arg2 [, ...]] Optional. Specifies the list of arguments.
toSource ( )*
Returns a string representing the source code of the current function.
toString ( )*
Returns a string representing the value of the current function. When a function needs to be converted to a string, the JavaScript interpreter automatically calls its toString method.

(*) - The method is inherited from the Function.prototype.

Examples:

Example 1:

A complete argument test.
function TestArguments (param1, param2) {
    var paramCount = TestArguments.length;
    var argCount = arguments.length;

    document.write ("Number of declared parameters: " + paramCount);
    document.write ("<br />");
    document.write ("Number of parameters specified by the caller: " + argCount);
    document.write ("<br />");

    for (var i = 0; i < argCount; i++) {
        document.write ("The value of the arguments[" + i + "] is " + arguments[i]);
        document.write ("<br />");
    }

    document.write ("The value of param1: " + param1);
    document.write ("<br />");
    document.write ("The value of param2: " + param2);
}
    

document.write ("call TestArguments ('first')");
document.write ("<br />");
TestArguments ('first');

document.write ("<br /><br />");

document.write ("call TestArguments ('first', 'second')");
document.write ("<br />");
TestArguments ('first', 'second');

document.write ("<br /><br />");

document.write ("call TestArguments ('first', 'second', 'third')");
document.write ("<br />");
TestArguments ('first', 'second', 'third');
Did you find this example helpful? yes no

Example 2:

This example shows how to implement a function that receives a variable-length argument list and returns their sum.
function Add () {
    var sum = 0;
    for (var i = 0; i < arguments.length; i++) {
        sum += arguments[i];
    }
    return sum;
}

var n = Add (2, 3);
document.write (n);  // 5

document.write ("<br />");

n = Add (1, 2, 3, 4, 5);
document.write (n);  // 15
Did you find this example helpful? yes no

Example 3:

This example shows how to use the apply method for variable-length argument lists.
function Add () {
    var sum = 0;
    for (var i = 0; i < arguments.length; i++) {
        sum += arguments[i];
    }
    return sum;
}

function Mul () {
    var product = 1;
    for (var i = 0; i < arguments.length; i++) {
        product *= arguments[i];
    }
    return product;
}

function AddAndMul () {
    sum = Add.apply (null, arguments);
    product = Mul.apply (null, arguments);
    return [sum, product];
}

var s = Add (1, 2, 3, 4, 5);
var p = Mul (1, 2, 3, 4, 5);
var sp = AddAndMul (1, 2, 3, 4, 5);

document.write (s);  // 15
document.write ("<br />");
document.write (p);  // 120
document.write ("<br />");
document.write (sp);  // 15, 120
document.write ("<br />");
Did you find this example helpful? yes no

Example 4:

This example shows how to call a method of an object in the context of another object with the apply method.
function Rectangle (a, b){
    this.a = a;
    this.b = b;
}

Rectangle.prototype.Area = function () {
    return this.a * this.b;
};

function Square (a) {
    var args = [a, a];
    Rectangle.apply (this, args);
}

Square.prototype = new Rectangle(); 

var rect = new Square (3);
document.write (rect.Area ());  // display: 9
Did you find this example helpful? yes no

Example 5:

This example shows how to call a method of an object in the context of another object with the call method.
function Rectangle (a, b){
    this.a = a;
    this.b = b;
}

Rectangle.prototype.Area = function () {
    return this.a * this.b;
};

function Square (a) {
    Rectangle.call (this, a, a);
}

Square.prototype = new Rectangle(); 

var rect = new Square (3);
document.write (rect.Area ());  // display: 9
Did you find this example helpful? yes no

Example 6:

In some cases, a code snippet needs to be evaluated at runtime. For example, when the response of an AJAX request contains some source code that needs to be executed by the JavaScript interpreter. In that case, we can use both the eval method and the Function object to solve the problem. The prefered solution is to use the Function object, because it is much more faster than the eval method (see eval for details).
This example uses the eval method:
var response = "2+3";
var result = eval (response);
document.write (result);    // 5
Did you find this example helpful? yes no

Example 7:

This example uses the Function object to implement the same functionality as the previous example:
var response = "2+3";
var result = (new Function ("return " + response)) ();
document.write (result);    // 5
Did you find this example helpful? yes no

External links:

User Contributed Comments

Post Content

Post Content