function Statement

See Also


Description
Declares a new function. See also Function Object
Syntax
function name([argument1 [, argument2 [, ...argumentn]]]) {    statements }
var name = function ( arguments ) stmt
var name = new Function ( arguments, stmt )

Arrow functions added in ECMAScript 2015:
var name = ( args ) => { stmt }

A "concise" body is assumed, where the expression is returned as if the body were { return expr }
var name = ( args ) => expr

Arrow functions combine nicely with array methods which accept a funtion. E.g.

var arr = [5, 6, 13, 0, 1, 18, 23];
var sum = arr.reduce((a, b) => a + b); //66
var even = arr.filter(v => v % 2 == 0); //[ 6, 0, 18]
var double = arr.map(v => v * 2); // [10, 12, 26, 0, 2, 36, 46]

and can produce cleaner promise chains

promise.then(a => {
// ...
}).then(b => {
// ...
});

They are the shortest way to provide an anonymous function:

setTimeout( () => {
  console.log('I happen sooner');
  setTimeout( () => {
    // deeper code
    console.log('I happen later');
  }, 1);
}, 1);

Note that arrow fuctions can be tricky:

Comma operator form (0, name()) This method of calling a function switches this from the local to the global this object. This may be useful because if you function.call(windows) you have to know the name of the global object. And depending on the environment, it might not be windows. E.g. Javascript running on a server, node, embedded, whatever. This pattern is supported in order to be able to process mutiple assignments in the for command: for (i=0, j=10; i < 10; i++,j--)
https://jsbin.com/kucutojono/edit?js,console

var x = "xGlobalFromWindow";
var obj = {
  x: "xLocalFromObject",
  getMyX: function() {
    return this.x;
    }
  }
console.log("(0, obj.getMyX)(): " + (0, obj.getMyX)() ); 
//"(0, obj.getMyX)(): xGlobalFromWindow"
console.log("obj.getMyX(): " + obj.getMyX() );
//"obj.getMyX(): xLocalFromObject"

The function statement syntax has the following parts:

Part Description
name The name of the function.
argument1...argumentn An optional, comma-separated list of arguments the function understands.
statements One or more JScript statements.

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


© 1997 by Microsoft Corporation. All rights reserved.

See also: