Unary Operator
Topic | Source |
---|---|
🧹 Clean Code | [Cast to Number in Javascript using the Unary (+) Operator |
The unary + operator converts its operand to Number type.
let positiveOne = +1
You don't need to parseInt
or parseFloat
.
So, to convert a string or a Boolean, or a Numeric String, you can just use +
.
+false // 0
+‘123’ // 123
+0xBABE // 47806 (Hexadecimal)
+null // 0
+function(val) {return val } // NaN
The Unary (+) can convert string representations of integers and floats, as well as the non-string values true, false, and null. Integers in both decimal and hexadecimal formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to NaN.
However, bear in mind that the Unary (+) does not perform well in certain cases. For example, it doesn't work as expected on empty strings, alphanumeric strings, empty objects etc.
+'' // NaN
+'123a' // NaN
+{} // NaN