Home > Articles

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

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
  • + Share This
  • 🔖 Save To Your Account