Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 1050638 of Default parameters

  • Revision slug: Web/JavaScript/Reference/Functions/Default_parameters
  • Revision title: Default parameters
  • Revision id: 1050638
  • Created:
  • Creator: mjroyappa
  • Is current revision? No
  • Comment fix typo "edge case" -> "edge cases"

Revision Content

{{jsSidebar("Functions")}}

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 {{jsxref("undefined")}}. However, in some situations it might be useful to set a different default value. This is where default parameters can help.

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, 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 {{geckoRelease(33)}}. Functions declared in the function body cannot be referred inside default parameters and throw a {{jsxref("ReferenceError")}} (currently a {{jsxref("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 {{geckoRelease(26)}}, the following code resulted in a {{jsxref("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
{{SpecName('ES6', '#sec-function-definitions', 'Function Definitions')}} {{Spec2('ES6')}} Initial definition.
{{SpecName('ESDraft', '#sec-function-definitions', 'Function Definitions')}} {{Spec2('ESDraft')}}  

Browser compatibility

{{CompatibilityTable}}
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support {{CompatChrome(49)}} {{CompatGeckoDesktop("15.0")}} {{CompatNo}} {{CompatNo}} {{CompatNo}}
Parameters without defaults after default parameters {{CompatChrome(49)}} {{CompatGeckoDesktop("26.0")}} {{CompatUnknown}} {{CompatUnknown}} {{CompatUnknown}}
Destructured parameter with default value assignment {{CompatNo}} {{CompatGeckoDesktop("41.0")}} {{CompatUnknown}} {{CompatUnknown}} {{CompatUnknown}}
Feature Android Android Webview Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support {{CompatNo}} {{CompatChrome(49)}} {{CompatGeckoMobile("15.0")}} {{CompatNo}} {{CompatNo}} {{CompatNo}} {{CompatChrome(49)}}
Parameters without defaults after default parameters {{CompatNo}} {{CompatChrome(49)}} {{CompatGeckoMobile("26.0")}} {{CompatUnknown}} {{CompatUnknown}} {{CompatUnknown}} {{CompatChrome(49)}}
Destructured parameter with default value assignment {{CompatNo}} {{CompatUnknown}} {{CompatGeckoMobile("41.0")}} {{CompatUnknown}} {{CompatUnknown}} {{CompatUnknown}} {{CompatUnknown}}

See also

Revision Source

<div>{{jsSidebar("Functions")}}</div>

<p><strong>Default function parameters</strong> allow formal parameters to be initialized with default values if no value or <code>undefined</code> is passed.</p>

<h2 id="Syntax">Syntax</h2>

<pre class="syntaxbox">
function [<em>name</em>]([<em>param1</em>[ = defaultValue1 ][, ..., <em>paramN</em>[ = defaultValueN ]]]) {
   <em>statements</em>
}
</pre>

<h2 id="Description">Description</h2>

<p>In JavaScript, parameters of functions default to <code>{{jsxref("undefined")}}</code>. However, in some situations it might be useful to set a different default value. This is where default parameters can help.</p>

<p>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 <code>undefined</code>. If in the following example, no value is provided for <code>b</code> in the call, its value would be <code>undefined</code>&nbsp; when evaluating <code>a*b</code> and the call to <code>multiply</code>&nbsp;would have returned <code>NaN</code>. However, this is caught with the second line in this example:</p>

<pre class="brush: js">
function multiply(a, b) {
  var b = typeof b !== 'undefined' ?  b : 1;

  return a*b;
}

multiply(5); // 5
</pre>

<p>With default parameters, the check in the function body is no longer necessary. Now, you can simply put <code>1</code> as the default value for <code>b</code> in the function head:</p>

<pre class="brush: js">
function multiply(a, b = 1) {
  return a*b;
}

multiply(5); // 5</pre>

<h2 id="Examples">Examples</h2>

<h3 id="Passing_undefined">Passing <code>undefined</code></h3>

<p>In the second call here, even if the second argument is set explicitly to <code>undefined</code> (though not <code>null</code>) when calling, the value of the <code>color</code> argument is the default one.</p>

<pre class="brush: js">
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' 
</pre>

<h3 id="Evaluated_at_call_time">Evaluated at call time</h3>

<p>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.</p>

<pre class="brush: js">
function append(value, array = []) {
  array.push(value);
  return array;
}

append(1); //[1]
append(2); //[2], not [1, 2]

</pre>

<p>This even applies to functions and variables:</p>

<pre class="brush: js">
function callSomething(thing = something()) { return thing }

function something(){
  return "sth";
}

callSomething();  //sth</pre>

<h3 id="Default_parameters_are_available_to_later_default_parameters">Default parameters are available to later default parameters</h3>

<p>Parameters already encountered are available to later default parameters:</p>

<pre class="brush: js">
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.")
</pre>

<p>This functionality is approximated in a straight forward fashion and demonstrates how many edge cases are handled.</p>

<pre class="brush: js">
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, "=^_^="]
</pre>

<h3 id="Functions_defined_inside_function_body">Functions defined inside function body</h3>

<p>Introduced in Gecko 33 {{geckoRelease(33)}}. Functions declared in the function body cannot be referred inside default parameters and throw a {{jsxref("ReferenceError")}} (currently a {{jsxref("TypeError")}} in SpiderMonkey, see {{bug(1022967)}}). Default parameters are always executed first, function declarations inside the function body evaluate afterwards.</p>

<pre class="brush: js">
// Doesn't work! Throws ReferenceError.
function f(a = go()) {
  function go(){return ":P"}
}
</pre>

<h3 id="Parameters_without_defaults_after_default_parameters">Parameters without defaults after default parameters</h3>

<p>Prior to Gecko 26 {{geckoRelease(26)}}, the following code resulted in a {{jsxref("SyntaxError")}}. This has been fixed in {{bug(777060)}} and works as expected in later versions:</p>

<pre class="brush: js">
function f(x=1, y) { 
  return [x, y]; 
}

f(); // [1, undefined]
</pre>

<h3 id="Destructured_parameter_with_default_value_assignment">Destructured parameter with default value assignment</h3>

<p>You can use default value assignment with the <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">destructuring assignment</a> notation:</p>

<pre class="brush: js">
function f([x, y] = [1, 2], {z: z} = {z: 3}) { 
  return x + y + z; 
}

f(); // 6</pre>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-function-definitions', 'Function Definitions')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td>Initial definition.</td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-function-definitions', 'Function Definitions')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td>&nbsp;</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>

<div>{{CompatibilityTable}}</div>

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</th>
   <th>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatChrome(49)}}</td>
   <td>{{CompatGeckoDesktop("15.0")}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
  </tr>
  <tr>
   <td>Parameters without defaults after default parameters</td>
   <td>{{CompatChrome(49)}}</td>
   <td>{{CompatGeckoDesktop("26.0")}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
  </tr>
  <tr>
   <td>Destructured parameter with default value assignment</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatGeckoDesktop("41.0")}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Android Webview</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>IE Mobile</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
   <th>Chrome for Android</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatChrome(49)}}</td>
   <td>{{CompatGeckoMobile("15.0")}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatChrome(49)}}</td>
  </tr>
  <tr>
   <td>Parameters without defaults after default parameters</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatChrome(49)}}</td>
   <td>{{CompatGeckoMobile("26.0")}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatChrome(49)}}</td>
  </tr>
  <tr>
   <td>Destructured parameter with default value assignment</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatGeckoMobile("41.0")}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

<h2 id="See_also">See also</h2>

<ul>
 <li><a class="external" href="https://wiki.ecmascript.org/doku.php?id=harmony:parameter_default_values" rel="external" target="_blank" title="https://wiki.ecmascript.org/doku.php?id=harmony:parameter_default_values">Original proposal at ecmascript.org</a></li>
</ul>
Revert to this revision