What's the significant use of unary plus and minus operators?

Javascript

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

The practical side of this is if you have a function that you need to return a number you can use

const result = +yourFunc()

instead of

const result = Number(yourFunc())

or

const result = -yourFunc()

instead of

const result = -Number(yourFunc())

It will return NaN the same way that Number().

IMO makes things a little harder to read, but could be useful to keep your lines short?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondragonflyView Question on Stackoverflow
Solution 1 - JavascriptBen ZottoView Answer on Stackoverflow
Solution 2 - JavascriptsirclesamView Answer on Stackoverflow