valueOf() vs. toString() in Javascript

The reason why (“x=”+x) gives “x=value” and not “x=tostring” is the following. When evaluating “+”, javascript first collects primitive values of the operands, and then decides if addition or concatenation should be applied, based on the type of each primitive.

So, this is how you think it works

a + b:
    pa = ToPrimitive(a)
    if(pa is string)
       return concat(pa, ToString(b))
    else
       return add(pa, ToNumber(b))

and this is what actually happens

a + b:
    pa = ToPrimitive(a)
    pb = ToPrimitive(b)*
    if(pa is string || pb is string)
       return concat(ToString(pa), ToString(pb))
    else
       return add(ToNumber(pa), ToNumber(pb))

That is, toString is applied to the result of valueOf, not to your original object.

For further reference, check out section 11.6.1 The Addition operator ( + ) in the ECMAScript Language Specification.


*When called in string context, ToPrimitive does invoke toString, but this is not the case here, because ‘+’ doesn’t enforce any type context.

Leave a Comment