Unary plus & minus operators in Typescript

The unary plus operator (+) precedes its operand and converts it into a number. If it fails to convert the operand into a number, then it returns NaN. The unary (-) operator converts the operand into a number and negates it.

Using Unary Plus & minus

Unary plus or minus operators require a single operand (hence the name unary) & precedes the operand.

In the following example, y is a string. We can place the unary plus (+) or minus (-) in front of it as shown below. It will convert it into a number and returns it.

The unary plus or minus operators follows these rules

  1. Tries to convert any operand to a number
  2. It converts empty string / Null to 0
  3. True is 1 and False is 0
  4. Converts Octal/Hexa numbers to decimal.
  5. Works correctly on scientific notation numbers.
  6. In case it fails to convert, then returns NaN

Examples of Unary plus

Unary plus converts the operand to a number. If it fails, then it returns NaN . The following shows how it works for different values.

Reference

  1. Expressions & Operators
  2. Precedence & Associativity

Read More

  1. Complete Typescript Tutorial
  2. Typescript Operators
  3. Arithmetic Operators
  4. Unary plus / Unary minus Operators
  5. Increment/Decrement Operators
  6. Comparison / Relational Operators
  7. Equality Operator / Strict Equality Operators
  8. Ternary Conditional Operators
  9. Logical Operators
  10. Bitwise Operators
  11. Assignment Operators
  12. Nullish coalescing operator
  13. Comma Operator in Typescript
  14. Operator Precedence

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top