How to set default parameters

Learn how to set default parameter values for JavaScript functions.

Default parameters

If you call a function in JavaScript without specifying arguments,Missing parametersIf the number of missing values is less than the declared number, the missing values will be set to: undefined.

Sometimes this is acceptable, but sometimes it is better to assign a default value to the parameters:

Example

function myFunction(x, y) {
  if (y === undefined) {
    y = 2;
  }
}

Try it yourself

ECMAScript 2015 Allow default parameter values in function declarations:

function myFunction (x, y = 2) {
  // function code
}

Try it yourself

Related pages

Manual:JavaScript funktion