[javascript] Is there a better way to do optional function parameters in JavaScript?

Ideally, you would refactor to pass an object and merge it with a default object, so the order in which arguments are passed doesn't matter (see the second section of this answer, below).

If, however, you just want something quick, reliable, easy to use and not bulky, try this:


A clean quick fix for any number of default arguments

  • It scales elegantly: minimal extra code for each new default
  • You can paste it anywhere: just change the number of required args and variables
  • If you want to pass undefined to an argument with a default value, this way, the variable is set as undefined. Most other options on this page would replace undefined with the default value.

Here's an example for providing defaults for three optional arguments (with two required arguments)

function myFunc( requiredA, requiredB,  optionalA, optionalB, optionalC ) {

  switch (arguments.length - 2) { // 2 is the number of required arguments
    case 0:  optionalA = 'Some default';
    case 1:  optionalB = 'Another default';
    case 2:  optionalC = 'Some other default';
    // no breaks between cases: each case implies the next cases are also needed
  }

}

Simple demo. This is similar to roenving's answer, but easily extendible for any number of default arguments, easier to update, and using arguments not Function.arguments.


Passing and merging objects for more flexibility

The above code, like many ways of doing default arguments, can't pass arguments out of sequence, e.g., passing optionalC but leaving optionalB to fall back to its default.

A good option for that is to pass objects and merge with a default object. This is also good for maintainability (just take care to keep your code readable, so future collaborators won't be left guessing about the possible contents of the objects you pass around).

Example using jQuery. If you don't use jQuery, you could instead use Underscore's _.defaults(object, defaults) or browse these options:

function myFunc( args ) {
  var defaults = {
    optionalA: 'Some default',
    optionalB: 'Another default',
    optionalC: 'Some other default'
  };
  args = $.extend({}, defaults, args);
}

Here's a simple example of it in action.

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to arguments

docker build with --build-arg with multiple arguments ARG or ENV, which one to use in this case? How to have multiple conditions for one if statement in python Gradle task - pass arguments to Java application Angularjs - Pass argument to directive TypeError: method() takes 1 positional argument but 2 were given Best way to check function arguments? "Actual or formal argument lists differs in length" Python: Passing variables between functions Print multiple arguments in Python