How TO - Set Default Parameters


Learn how to set default parameter values for JavaScript functions.


Default Parameters

If a function in JavaScript is called with missing arguments (less than declared), the missing values are set to undefined.

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

Example

function myFunction(x, y) {
  if (y === undefined) {
    y = 2;
  }
}
Try it Yourself »

ECMAScript 2015 allows default parameter values in the function declaration:

function myFunction (x, y = 2) {
  // function code
}
Try it Yourself »

Read more about functions in our JavaScript Function Tutorial.


Copyright 1999-2023 by Refsnes Data. All Rights Reserved.