Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

3.11 Default Arguments

In the preceding section, you saw how to implement a function that is called with fewer arguments than parameters. Instead of manually checking for undefined argument values, you can provide default arguments in the function declaration. After the parameter, put an = and an expression for the default—that is, the value that should be used if no argument was passed.

Here is another way of making the average function work with one argument:

const average = (x, y = x) => (x + y) / 2

If you call average(3), then y is set to x—that is, 3—and the correct return value is computed.

You can provide multiple default values:

const average = (x = 0, y = x) => (x + y) / 2

Now average() returns zero.

You can even provide a default for the first parameter and not the others:

const average = (x = 0, y) => y === undefined ? x : (x + y) / 2

If no argument (or an explicit undefined) is supplied, the parameter is set to the default or, if none is provided, to undefined:

average(3) // average(3, undefined)
average() // average(0, undefined)
average(undefined, 3) // average(0, 3)
  • + Share This
  • 🔖 Save To Your Account