default parameters Redirect 1

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

Warning: For Gecko 15 and upper versions.

Syntax

function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) {
   statements
}

Examples

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

multiply(5); // 5

 

For Gecko versions lower than 15, default parameters syntax does not work: 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:

function multiply(a, b) {
  b = typeof b !== 'undefined' ?  b : 1;

  return a*b;
}

multiply(5); // 5

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 (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

Document Tags and Contributors

Contributors to this page: Sheppy
Last updated by: Sheppy,