How Does Type Coercion With "+string" Work In Javascript?
Solution 1:
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
Solution 2:
The unary plus operator is the same as unary minus. You are probably familiar with this syntax:
const a = 1;
console.log(-a); // -> -1
What happens is the value of a
is type-casted to Number, and then the operation is applied to resulting value. This is why you will end up with NaN
if you try to apply unary operator to a string, say
const a = 'abc';
console.log(-a); // -> NaN
although the string "123"
will be successfully type-casted to a Number 123
, and you'll see -123
:
const a = '123';
console.log(-a); // -> -123
The +
works the same way but it doesn't negate the value. So if you do
+123
the value will remain 123
. If you do
+'abc'
the value will be NaN
, just as in case with -'abc'
. But if you do
+'123'
then "123"
(string) will be type-casted to 123
(number), applied with +
(nothing happens to the number), and returned. So you'll end up with 123
(number).
Post a Comment for "How Does Type Coercion With "+string" Work In Javascript?"