Operator arity

Arity refers to how many operands (or inputs) an operator can receive. An operand is a formal term for the value(s) that you can give or pass to an operator.

If we consider the greater-than operator (>), it receives two operands:

a > b

In this example, a is its first operand (or left-side operand). And b is its second (or right-side operand). Since it receives two operands, the greater-than operator is considered a binary operator. In JavaScript, we have unary, binary, and ternary operators:

// Unary operator examples (one operand)
-a
!a

// Binary operator examples (two operands)
a == b
a >= b

// Ternary operator examples (three operands)
a ? b : c
There is only one ternary operator in JavaScript, the conditional operator (a ? b : c). Since it is the only ternary operator, it is sometimes simply referred to as the ternary operator instead of its formal name.

Knowing about the arity of a given operator is vital—just as it would be vital to know how many arguments to pass a function. It's also important to consider how we are communicating our intent when we compose operations. Since operations can appear in series, it can sometimes be unclear which operator refers to which operand. Consider this confusing expression:

foo + + baz - - bar

To avoid confusion in understanding operations like this, it is conventional to move unary operators closer to their operands and even to employ parentheses to make it absolutely crystal clear what the intent is:

foo + (+baz) - (-bar)

As with all of the parts of code, operators must be wielded with care and concern for the individual or individuals (including your future self) who'll have to encounter, understand, and maintain the code going forward.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.190.144