Home > Articles

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

This chapter is from the book

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, the average function 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 argument x conforms to a given type.

Table 3-1 Type Tests

Type

Test

Notes

String

typeof x === 'string' ||
  x instanceof String

x might be constructed as new String(. . .)

Regular expression

x instanceof RegExp

 

Number

typeof x === 'number' ||
  x instanceof Number

x might be constructed as new 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'

 

  • + Share This
  • 🔖 Save To Your Account