␡
- 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
This chapter is from the book
3.10 Supplying More or Fewer Arguments
Suppose a function is declared with a particular number of parameters, for example:
const average = (x, y) => (x + y) / 2
It appears as if you must supply two arguments when you call the function. However, that is not the JavaScript way. You can call the function with more arguments—they are silently ignored:
let result = average(3, 4, 5) // 3.5—the last argument is ignored
Conversely, if you supply fewer arguments, then the missing ones are set to undefined. For example, average(3) is (3 + undefined) / 2, or NaN. If you want to support that call with a meaningful result, you can:
const average = (x, y) => y === undefined ? x : (x + y) / 2