How to set default parameters

Learn how to set default parameter values for JavaScript functions.

Default parameters

If a function is called in JavaScriptMissing parametersIf the number of missing values is (less than the number declared), 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

Tutorial:JavaScript Function