default parameters

Did you know that you can read content offline by using one of these tools? If you would like to read offline MDN content in another format, let us know by commenting on Bug 665750.

Dash App
  • Tags
  • Files

Allow formal parameters to be initialized with default values if no value or undefined is passed.

Syntax

function f(a, b = 37) {
  // when called, if no value or undefined is passed as second argument, b will have 37 as value.
}

Examples

function multiply(a, b = 1) {
  return a*b;
}

multiply(5); // 5

Before default parameters,  if no value is provided for b in the call, its value would be undefined  when evaluating a*b and the call to multiple would have returned NaN;. So the general strategy for setting defaults is to test parameter values in the body of the function and assign a value if they're undefined:

b = typeof b == 'undefined'?  b : 1;

Here's another example:

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' 

For the second case, even if the second argument is set explicitly to undefined when calling, the value of the color argument is the default one.

function append(value, array = []) {
  array.push(value);
  return array;
}

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

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.
This even applies to functions and variables:

function callSomething(thing = something()) { return thing }

callSomething(); //throws a ReferenceError

let (something = function() "sth") {
  callSomething(); //"sth"
}

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support Not supported 15.0 (15) Not supported Not supported Not supported
Feature Android Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
Basic support Not supported 15.0 (15) Not supported Not supported Not supported

Specification

See also