Cast to Number in Javascript using the Unary (+) Operator

Nikhil John
2 min readOct 5, 2016

--

The Unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number

Unary plus (+)

Unary operators work on single operands. The Unary (+) operator is no different, and it precedes it’s operand.

var positiveOne = +1

Now that looks like useless code. But wait. Let’s look at it’s specification from the ECMA specs:

The unary + operator converts its operand to Number type.

That’s right. So you don’t need to parseInt or parseFloat everything. And you sure don’t need to use Number()!

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

There are of course other ways to cast to Number in Javascript, including but not limited to:

For a full chart of what works when, please refer here. I have taken the liberty to borrow the chart below:

Javascript Number conversions

Happy coding!

--

--

Nikhil John

Tips and tricks on Travelling and Web Engineering! Senior Engineer @Microsoft