HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

JavaScript function arity

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptarityfunction

Problem

Function arity is the number of arguments a function expects. While it sounds very theoretical, it's actually quite useful in practice, especially in functional programming.
The arity of a function can be easily retrieved using Function.prototype.length.
As you can see in the example above, the arity of a function is the number of parameters it expects. This is true for regular functions but not for variadic functions. A variadic function is a function that accepts a variable number of arguments. In that case, Function.prototype.length will return 0.
In some cases, we might want to limit the number of arguments a function can accept. This comes in handy for variadic functions, especially when combined with currying.
A nullary function is a function that accepts no arguments. In that case, we can simply call the function without any arguments.

Solution

const arity = fn => fn.length;

arity(Math.sqrt); // 1
arity(Math.pow); // 2
arity((x, y, z) => x + y + z); // 3
arity((...args) => args); // 0


As you can see in the example above, the arity of a function is the number of parameters it expects. This is true for regular functions but not for variadic functions. A variadic function is a function that accepts a variable number of arguments. In that case, Function.prototype.length will return 0.
In some cases, we might want to limit the number of arguments a function can accept. This comes in handy for variadic functions, especially when combined with currying.
A nullary function is a function that accepts no arguments. In that case, we can simply call the function without any arguments.
A unary function is a function that accepts exactly one argument and can be created by calling the function with just the first argument provided.
A binary function is a function that accepts exactly two arguments. Similarly to the unary function, we can create a binary function by calling the function with just the first two arguments provided.
In general, a n-ary function is a function that accepts exactly n arguments. Using Array.prototype.slice() and the spread operator (...), we can create a function that will call the provided function with the first n arguments.

Code Snippets

const arity = fn => fn.length;

arity(Math.sqrt); // 1
arity(Math.pow); // 2
arity((x, y, z) => x + y + z); // 3
arity((...args) => args); // 0
const nullary = fn => () => fn();

nullary(Math.random)(); // 0.6019623086
const unary = fn => val => fn(val);

['6', '8', '10'].map(unary(Number.parseInt)); // [6, 8, 10]

Context

From 30-seconds-of-code: function-arity

Revisions (0)

No revisions yet.