[Solved] How does type coercion with “+string” work in Javascript? [duplicate]


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

2

solved How does type coercion with “+string” work in Javascript? [duplicate]