gator gator - 4 months ago 27
Javascript Question

How does type coercion with "+string" work in Javascript?

I came across this recently, "+string" converting the string to a number (specifically, using the plus operator in front of a string or string variable for type coercion), but wasn't able to find documentation or discussion that satisfied my interested. I get the impression it's lazy or could have unintended side effects, but I want to understand it better. Any insight is appreciated.


As the ECMAScript spec describes in section 12.5.6:

12.5.6 Unary + Operator

NOTE       The unary + operator converts its operand to Number type.

So in JavaScript, the unary + operator (e.g., +x) will always convert the expression x into a number. In other words, the following statements are equivalent:

var x = Number('1234');
var y = +'1234';

This also works on any variable, not only strings or numbers. If the object you try to convert is not an string or number, then the toString() method of that object will be called to convert the object into a string, and then that will be converted into a number. For example:

var obj = {
  toString: function() { return '9999'; }
var num = +obj; // = 9999