- 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.9 Testing Argument Types
In JavaScript, you do not specify the types of function arguments. Therefore, you can allow callers to supply an argument of one type or another, and handle that argument according to its actual type.
As a somewhat contrived example, theaveragefunction may accept either numbers or arrays.
const average = (x, y) => { let sum = 0 let n = 0 if (Array.isArray(x)) { for (const value of x) { sum += value; n++ } } else { sum = x; n = 1 } if (Array.isArray(y)) { for (const value of y) { sum += value } } else { sum += y; n++ } return n === 0 ? 0 : sum / n }
Now you can call:
result = average(1, 2) result = average([1, 2, 3], 4) result = average(1, [2, 3, 4]) result = average([1, 2], [3, 4, 5])
Table 3-1 shows how to test whether an argumentxconforms to a given type.
Table 3-1Type Tests
Type |
Test |
Notes |
---|---|---|
String |
typeof x === 'string' || x instanceof String |
xmight be constructed asnew String(. . .) |
Regular expression |
x instanceof RegExp |
|
Number |
typeof x === 'number' || x instanceof Number |
xmight be constructed asnew Number(. . .) |
Anything that can be converted to a number |
typeof +x === 'number' |
Obtain the numeric value as+x |
Array |
Array.isArray(x) |
|
Function |
typeof x === 'function' |