A binary operator is an operator that uses two values, while a unary operator only uses one.
Take, for example, the typeof operator. You give it a value and it’ll tell you what type that value is.
Is the typeof operator binary or unary?
Guess what the typeof operator it is, unary or binary?
It’s unary! It takes exactly one value.
Let’s start with some examples below.
Examples of using the typeof operator
Example 1: Giving the typeof operator a number
console.log(typeof 4.5);
Guess what it outputs…
It outputs:
number
Example 2: Giving the typeof operator a string
How about if you added in something like “this is a number”?
console.log("this is a number");
And the output is…
string
You can’t trick the operator, it knows it’s a string because of the double-quotations.
What are some examples of binary operators?
Operators such as the arithmetic operators are all mostly binary operators because they each take exactly two values.
For example:
3 * 4
2 + 5
33 % 3
2 - 5
75 / 3
These are all binary.
However, there’s one operator in this list that can exist as both.
The minus operator can be both unary and binary
Under the right circumstances, the minus operator can be either unary or binary.
You can subtract two different values like in the example code shown above but, you can also have a negative number like so:
-3
See how the minus operator uses only a single value?
Anytime there is a negative number, the minus sign becomes a unary operator.
In the case above, that makes it a unary operator.