Unary plus & minus operators in JavaScript

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

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