Export (0) Print
Expand All

function Statement (JavaScript)

Declares a new function.

function functionname ([arg1 [, arg2 [,...[, argN]]]]) {
    statements
} 

functionname

Required. The name of the function.

arg1...argN

Optional. An optional, comma-separated list of arguments the function understands.

statements

Optional. One or moreJavaScript statements.

Use the function statement to declare a function for later use. The code that is contained in statements is not executed until the function is called from elsewhere in the script.

The return statement is used to return a value from the function. You do not have to use a return statement; the program will return when it reaches the end of the function. If no return statement is executed in the function, or if the return statement has no expression, the function returns the value undefined.

Note Note

When you call a function, be sure to include the parentheses and any required arguments. Calling a function without parentheses returns a reference to the function, not the results of the function.

The following example illustrates the use of the function statement.

function myfunction (arg1, arg2) {
    var r = arg1 * arg2;
    return(r);
}

A function can be assigned to a variable. This is illustrated in the following example.

function AddFive(x) {
    return x + 5;
}

function AddTen(x) {
    return x + 10;
}

var condition = false;

var MyFunc;
if (condition) {
    MyFunc = AddFive;
}
else {
    MyFunc = AddTen;
}

var result = MyFunc(123);
// Output: 133

Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, Internet Explorer 10 standards, Internet Explorer 11 standards. Also supported in Store apps (Windows 8 and Windows Phone 8.1). See Version Information.

Show:
© 2014 Microsoft