This page is Ready to Use

Notice: The WebPlatform project, supported by various stewards between 2012 and 2015, has been discontinued. This site is now available on github.

function

Summary

Declares a new function.

Syntax

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.

Examples

The following example illustrates the use of the function statement.

//Defining the function myFunc
function myFunc () {
    var r = 3 * 4;
    return(r);
}

//Calling the function
myFunc();

//Output: 12

It’s possible to pass along arguments within the parantheses when calling the function.

//Defining the function myFunc
function myFunc (name) {
    console.log('Hello, ' + name + '!');
}

//Calling the function
myFunc('Susan');

//Output: Hello, Susan!

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

Remarks

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

See also

Other articles

Attributions

  • Microsoft Developer Network: Article