An operator is a symbol that define the operation to do between 1 o more operands.
We use a lot of operators: sum (+), subtraction (-), multiply (*), division (/), logic and (&&), negation (!),…
A unary operator is an operator that only needs one operand to work.
In this example we have an operand (
i) and an operator (
++), we don’t need more to increment the
i variable value.
++Increment. Increments the value of operand in one unit.
--Decrement. Decrements the value of operand in one unit.
!Logical not. Negate the boolean operand value.
-Negation. Negate the numeric operand value.
typeofReturns the type of the operand in a string.
deleteDeletes the index of an array or an object.
There is another unary operator that I haven’t talked about, the unary addition (
let a = 10
What do you think will be the result? You probably right:
So what is this operator for if returns the same value? Here is another example.
let a = '10'
In this one, what do you think will be the result? Yes, it’s
10 but not the same
10 we had. What?
Replay, but now let’s look at the types
let a = 10
Both results are
number. Here is the point, this operator (tries to) convert the value to number. So we can use it to cast values to
console.log(+'10a') // NaN
Take care with the last result because it’s less obvious
Unary minus do the same, but negate the result.
! operator behaves similarly: It tries to convert the value to
boolean, but negate the result of the cast, but if we double negate the value we found a way to cast values to
console.log(!!'10a') // true
I marked the results that for me are counterintuitive
This two unary operators,
!, using as
!! are very useful to cast to number and boolean respectively.
Enjoy them! 😉