Defining Default Values for Parameters

Parameters can take default values that step in for any missing arguments.

Advantages of default parameters

We can benefit from default parameters in one of three ways:

  1. As a user of a function, we don’t have to pass in a value for a parameter if the value we intend to send is the same as the sensible default chosen by the creator of the function. This results in less work and reduced noise/clutter in code.
  2. As the author of a function, we can evolve the function signature more freely to add a new parameter without breaking the existing code.
  3. We can compensate for the lack of function overloading in JavaScript. Many modern languages provide function overloading, but JavaScript does not. With default parameters, the caller may pass a different number of parameters, giving the illusion of using overloaded functions.

Let’s explore the parameters feature’s default values with an evolving function example.

Example

Suppose we want to implement a function to sort a given array of books based on their titles. We can readily write this function, like so:

Get hands-on with 1200+ tech skills courses.