Understanding the concept of arity is crucial to understanding function anatomy. It refers to the number of parameters the function in question expects. While it's a simple concept, it's necessary to understand it before discussing more advanced topics like functional programming, currying, and variadic functions.
Let's dive in and take a look.
The arity of a function is the measure of how many parameters it expects. A function that expects one parameter, for example, is said to have an arity of one. A function that expects three parameters, is said to have an arity of three.
The arity of a function is the measure of how many parameters it expects.
Parameters vs arguments
When talking about arity, it’s important to differentiate between function parameters and function arguments.
Function parameters are the dynamic variables that the function accepts when its defined. In other words, the arity is determined at the time of function definition.Compare that to function arguments, which are the values that are passed in to it when the function is called.
Examples of arity
A nullary function
A nullary function is a function that has no inputs. Presumably it processes data in some way or another, but does so independent of inputs.
The use cases for a nullary function can be various:
- It can return a non-dynamic value that is independent of the inputs.
- It can affect a value outside of the function, causing a side-effect.
A unary function
A unary function accepts one parameter. Presumably, the output of the function is dependent on that parameter, but it doesn't strictly have to be the case by definition.
A binary function
A binary function accepts two parameters. The output of the function presumably acts on those two parameters, but it doesn't necessarily have to be the case.
Here's a correlative with ES6 string literals.
A trinary function
You guessed it: trinary functions have an arity of 3, meaning they accept three inputs. They can make use of these inputs in their outputs, or not - by definition.
An N-ary function
We can abstract to higher arity functions; we call them n-ary functions, where $n$ is simply the number of parameters the function accepts.