Converting to a number using unary plus operator

Question | Dec 29, 2015 | hkumar 

Suppose you have to convert:

  1. A boolean to a number - true to 1 and false to 0
  2. A numeric string to a number - '30' to 30 or '35.3' to 35.3

For the first case you can use a ternary operator like - "aNum = aBool ? 1 : 0".
For the second case you can call parseFloat.

Or alternatively you can use the Javascript's magical unary plus operator to do both:

var b = true;
var s = '100';
var n1 = +b; // 1 
var n2 = +s; // 100

Isn't it neat?

When it comes to converting from numeric strings unary plus has few differences with parseFloat and parseInt.

Works with hexadecimal and exponential formats
The built-in functions parseFloat and parseInt are inconsistent when it comes to parsing hexadecimal and exponential number formats. Unary plus does exactly what you would expect:

var hn1 = +'0xFF'; // 255
var hn2 = parseInt('0xFF'); // 255
var hn3 = parseFloat('0xFF'); // 0 

var en1 = +'3e2';   // 300
var en2 = parseInt('3e2');   // 3 
var en3 = parseFloat('3e2');   // 300

String must be strictly numeric
Both parseFloat and parseInt can parse the string even if it is not strictly a number, whereas unary plus expects string to have strictly a number. It depends upon how you look at it but I consider this to be an advantage of unary plus because it saves you from some unexpected behaviors.

var sn1 = +'23a'; // NaN
var sn2 = parseInt('23a'); // 23
var sn3 = parseFloat('23a'); // 23

Empty string is converted to 0
When it comes to empty string, unary plus - very unexpectedly - converts it to 0. I consider it a big drawback of unary plus:

var zn1 = +''; // 0
var zn2 = parseInt(''); // NaN
var zn3 = parseFloat(''); // NaN

There is quite a useful pattern that seasoned Javascript developers use to toggle a number between 0 and 1. Use what you learned above to answer this question:

var v = 1;
v = +!v;

What would be the value of v?