- 3.1 Declaring Functions
- 3.2 Higher-Order Functions
- 3.3 Function Literals
- 3.4 Arrow Functions
- 3.5 Functional Array Processing
- 3.6 Closures
- 3.7 Hard Objects
- 3.8 Strict Mode
- 3.9 Testing Argument Types
- 3.10 Supplying More or Fewer Arguments
- 3.11 Default Arguments
- 3.12 Rest Parameters and the Spread Operator
- 3.13 Simulating Named Arguments with Destructuring
- 3.14 Hoisting
- 3.15 Throwing Exceptions
- 3.16 Catching Exceptions
- 3.17 The finally Clause
- Exercises
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)