function

function – Declares a function with the specified parameters.

Description

function ([mixed param, …])

Parameters

Name Description Type Default Optional
param, … Variables to pass into the function. mixed Yes

Changelog

Version Description
ES 6 Ability to set default values in function declaration.
ES 6 Agregating parameter overflow.

Examples

Example #1 – function example

Basic syntax for creating a function.

function f (a, b) { return a + b; } console.log(f(1, 2)); // 3

We can also declare a function by assigning a variable to an unnamed function.

var f = function (a, b) { return a + b; } console.log(f(1, 2)); // 3
Example #2 – function example

Create a self executing function.

(function () { console.log('Executed.'); // Executed. })();

Passing variables into a self executing function.

(function (a, b) { console.log(a, b); // Hello world })('Hello', 'world');
Example #3 – function example

In javascript you do not need to pass any of the functions parameters. So if you wish to create parameters with default values, you can use something like the example below where the b parameter will be set to a default value if it is not passed when calling the function.

function f (a, b) { if (b === undefined) { // Second parameter not passed b = 2; } return a * b; } var r = f(2); console.log(r); // 4 console.log(f(2, 4)); // 8

A shorthand version.

function f (a, b) { b = b || 2; return a * b; } var r = f(2); console.log(r); // 4 console.log(f(2, 4)); // 8
Example #4 – function example

Accessing arguments passed to the function.

function f (params) { console.log(arguments); } f('foo', 'bar');
Example #5 – function example

Setting default values. Available from ES 6.

function f (a = 1, b = 2) { return a + b; } console.log(f());
Example #6 – function example

Agregating parameter overflow. Available from ES 6.

function f (...params) { console.log(params); console.log(params[0]); console.log(params[1]); } f('foo', 'bar');
Example #7 – function example

Spreading variable in function call. Available from ES 6.

function f (foo, bar) { console.log(foo, bar); } var params = ['Hello', 'world']; f(...params);
Example #8 – function example

Spreading variable in function call. Available from ES 6.

'use strict'; function f (foo, bar) { return {foo: foo, bar: bar}; } var params = ['Hello', 'world']; var {foo, bar} = f(...params); console.log(foo);

See also

External references