The Unary Plus Operator ( + )

The Unary Minus Operator ( - )

Navigation Aids -- This Page | Navigation Aids -- This Topic | Navigation Aids -- This Site | ||
---|---|---|---|---|

- precedence
- associativity
- unary operator
- unary plus operator
- unary minus operator
- number value
- number type
- number operand
- negation
- No Op: since the unary plus operator performs no real operation, it has been referred to as the "no op" operator.

This page will show the basic rules for the JavaScript unary plus and minus operator sub-group. Some special situation cases are explained. And finally, some scripting examples are provided with comments.

- The unary plus and minus operators have the following in common:
- The unary plus and minus operators are unary operators.
- They have a "right-to-left" associatively.
- They have a precedence of 14.
- They take a number operand type.
- The result of these operators is that they return a number, but leave the original operand unchanged.
- They will attempt to covert non-numeric values to a number.
- They will return NaN if the numeric conversion fails.
- They will return NaN if the operand is NaN.

- The unary plus behaves as follows:
- The unary plus operator basically does not affect the sign of an integer. If the integer is a negative number the unary plus will not change the sign to a positive.
- Other than a possible type conversion, this operator does nothing.

- The unary minus behaves as follows:
- The unary minus will return a positive number, if the operand is negative.
- The unary minus will return a negative number, if the operand is positive.
- Negating -0 produces +0 and negating +0 produces -0.

- Note that the unary plus and minus operators are different than the addition and subtraction operators. Same symbols; but applied differently.

Expression | y = | Comment |
---|---|---|

var x = 4; y = +x; |
4 | unary plus the unary plus has no effect on a number (no op) |

var x = "abc"; y = +x; |
NaN | unary plus the unary plus returns NaN for non-numeric operands; in this case, the operand could not be converted to a number |

var x = "5"; y = +x; |
5 | unary plus the unary plus returns 5; in this case, the operand could be converted to a number |

var x = 4; y = -x; |
-4 | unary minus the unary minus returns the negation of the operands value |

var x = -4; y = -x; |
4 | unary minus the unary minus returns the negation of the operands value |