If unary +
/-
operators are used to perform conversions as the Number()
casting function, then why do we need unary operators? What's the special need of these unary operators?
The - (unary minus) operator negates the value of the operand. The operand can have any arithmetic type. The result is not an lvalue. For example, if quality has the value 100 , -quality has the value -100 .
The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean. The increment/decrement operators can be applied before (prefix) or after (postfix) the operand.
Unary operators work on one value. Unary plus ( + ) or minus ( - ) converts a non-numeric value into a number. The unary minus negates the value after the conversion. The prefix increment operator adds one to a value.
Unary operator in C++ It operates on a pointer variable and returns an l-value equivalent to the value at the pointer address. This is called "dereferencing" the pointer. The unary address-of operator (&) takes the address of its operand.
The Unary +
operator converts its operand to Number type. The Unary -
operator converts its operand to Number type, and then negates it. (per the ECMAScript spec)
In practice, Unary -
is used for simply putting negative numbers in normal expressions, e.g.:
var x = y * -2.0;
That's the unary minus operator at work. The Unary +
is equivalent to the Number() constructor called as a function, as implied by the spec.
I can only speculate on the history, but the unary +/- operators behave similarly in many C-derived languages. I suspect the Number() behavior is the addition to the language here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With