Os nossos voluntários ainda não traduziram este artigo para Português (Europeu) . Junte-se a nós e ajude-nos a fazer o trabalho!
Default function parameters allow formal parameters to be initialized with default values if no value or undefined
is passed.
Syntax
function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) { statements }
Description
In JavaScript, parameters of functions default to
. However, in some situations it might be useful to set a different default value. This is where default parameters can help.undefined
In the past, the general strategy for setting defaults was to test parameter values in the body of the function and assign a value if they are undefined
. If in the following example, no value is provided for b
in the call, its value would be undefined
when evaluating a*b
and the call to multiply
would have returned NaN
. However, this is caught with the second line in this example:
function multiply(a, b) { var b = (typeof b !== 'undefined') ? b : 1; return a*b; } multiply(5); // 5
With default parameters in ES6, the check in the function body is no longer necessary. Now, you can simply put 1
as the default value for b
in the function head:
function multiply(a, b = 1) { return a*b; } multiply(5); // 5
Examples
Passing undefined
In the second call here, even if the second argument is set explicitly to undefined
(though not null
) when calling, the value of the color
argument is the default one.
function setBackgroundColor(element, color = 'rosybrown') { element.style.backgroundColor = color; } setBackgroundColor(someDiv); // color set to 'rosybrown' setBackgroundColor(someDiv, undefined); // color set to 'rosybrown' too setBackgroundColor(someDiv, 'blue'); // color set to 'blue'
Evaluated at call time
The default argument gets evaluated at call time, so unlike e.g. in Python, a new object is created each time the function is called.
function append(value, array = []) { array.push(value); return array; } append(1); //[1] append(2); //[2], not [1, 2]
This even applies to functions and variables:
function callSomething(thing = something()) { return thing } function something(){ return "sth"; } callSomething(); //sth
Default parameters are available to later default parameters
Parameters already encountered are available to later default parameters:
function singularAutoPlural(singular, plural = singular+"s", rallyingCry = plural + " ATTACK!!!") { return [singular, plural, rallyingCry ]; } //["Gecko","Geckos", "Geckos ATTACK!!!"] singularAutoPlural("Gecko"); //["Fox","Foxes", "Foxes ATTACK!!!"] singularAutoPlural("Fox","Foxes"); //["Deer", "Deer", "Deer ... change."] singularAutoPlural("Deer", "Deer", "Deer peaceably and respectfully petition the government for positive change.")
This functionality is approximated in a straight forward fashion and demonstrates how many edge cases are handled.
function go() { return ":P" } function withDefaults(a, b = 5, c = b, d = go(), e = this, f = arguments, g = this.value) { return [a,b,c,d,e,f,g]; } function withoutDefaults(a, b, c, d, e, f, g){ switch(arguments.length){ case 0: a case 1: b = 5 case 2: c = b case 3: d = go(); case 4: e = this case 5: f = arguments case 6: g = this.value; default: } return [a,b,c,d,e,f,g]; } withDefaults.call({value:"=^_^="}); // [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="] withoutDefaults.call({value:"=^_^="}); // [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="]
Functions defined inside function body
Introduced in Gecko 33 (Firefox 33 / Thunderbird 33 / SeaMonkey 2.30). Functions declared in the function body cannot be referred inside default parameters and throw a ReferenceError
(currently a TypeError
in SpiderMonkey, see bug 1022967). Default parameters are always executed first, function declarations inside the function body evaluate afterwards.
// Doesn't work! Throws ReferenceError. function f(a = go()) { function go(){return ":P"} }
Parameters without defaults after default parameters
Prior to Gecko 26 (Firefox 26 / Thunderbird 26 / SeaMonkey 2.23 / Firefox OS 1.2), the following code resulted in a SyntaxError
. This has been fixed in bug 777060 and works as expected in later versions:
function f(x=1, y) { return [x, y]; } f(); // [1, undefined]
Destructured parameter with default value assignment
You can use default value assignment with the destructuring assignment notation:
function f([x, y] = [1, 2], {z: z} = {z: 3}) { return x + y + z; } f(); // 6
Specifications
Specification | Status | Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Function Definitions' in that specification. |
Standard | Initial definition. |
ECMAScript 2017 Draft (ECMA-262) The definition of 'Function Definitions' in that specification. |
Draft |
Browser compatibility
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | 49 | 15.0 (15.0) | No support | No support | No support |
Parameters without defaults after default parameters | 49 | 26.0 (26.0) | ? | ? | ? |
Destructured parameter with default value assignment | 49 | 41.0 (41.0) | ? | ? | ? |
Feature | Android | Android Webview | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android |
---|---|---|---|---|---|---|---|
Basic support | No support | 49 | 15.0 (15.0) | No support | No support | No support | 49 |
Parameters without defaults after default parameters | No support | 49 | 26.0 (26.0) | ? | ? | ? | 49 |
Destructured parameter with default value assignment | No support | ? | 41.0 (41.0) | ? | ? | ? | ? |