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?
Asked
Active
Viewed 1.3k times
56
![](../../users/profiles/402884.webp)
Chris Martin
- 28,558
- 6
- 66
- 126
![](../../users/profiles/629305.webp)
dragonfly
- 2,797
- 6
- 23
- 47
1 Answers
76
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.
![](../../users/profiles/73297.webp)
Ben Zotto
- 67,174
- 23
- 136
- 201