Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 595
dragonfly Avatar asked Mar 27 '11 15:03

dragonfly


People also ask

What is the significance of unary minus operator?

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 .

What is the use of unary operators?

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.

What are plus and minus operators in unary?

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.

What is the use of unary operator in C++?

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.


1 Answers

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.

like image 113
Ben Zotto Avatar answered Oct 14 '22 15:10

Ben Zotto