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.
Table of Contents
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.
1 2 3 4 5 6 7 8 9 | let y = "1"; console.log(typeof(y)); //string console.log(typeof(+y)); //number console.log(+y); //1 console.log(-y); //-1 |
1 2 3 4 5 6 | let y="-1" console.log(+y); //-1 console.log(-y); //1 |
The unary plus or minus operators follows these rules
- Tries to convert any operand to a number
- It converts empty string /
Null
to 0 True
is 1 andFalse
is 0- Converts Octal/Hexa numbers to decimal.
- Works correctly on scientific notation numbers.
- 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | console.log(+"100") //100 console.log(+"100.5175") //100.5175 //Empty string & null is zero console.log(+"") //0 console.log(+" ") //0 console.log(+null) //0 //Undefined console.log(+undefined) //Nan //Infinity console.log(+Infinity) //Infinity //Boolean console.log(+true) //1 console.log(+false) //0 //Hexadecimal console.log(+"0x22") //34 console.log(+"0022") //22 console.log(+"0o51") //41 console.log(+"3.125e7") //31250000 //If fails to convert to number, then returns NaN console.log(+"10AA0.5175") //NaN console.log(+"35 35") //NaN console.log(+"AB 35") //NaN console.log(+'hello'); //NaN |
Reference
Read More
- JavaScript Tutorial
- JavaScript Operators
- Arithmetic Operators
- Unary plus (+) & Unary minus (-)
- Increment & Decrement Operators
- Comparison or Relational Operators
- Strict Equality & Loose Equality Checker
- Ternary Conditional Operator
- Logical Operators
- Bitwise Operators
- Assignment Operators
- Nullish Coalescing Operator
- Comma Operator
- Operator Precedence