Reputation: 838
I am reading the Book, YDKJS by Kyle Simpson, topic Coercion. While looking at the specs I found that ToPrimitive calls OrdinaryToPrimitive conditionally. I read in a blog that:
JavaScript view objects with [Symbol.ToPrimitive] method as exotic and the exoticToPrim property become defined
That means if the exoticToPrim property for an object is undefined, OrdinaryToPrimitive is called.
Example:
1. var a = 42;
2. a + " ";
3. String(a);
My Queries (How Coercion working under the Hood) :
Note: I know what Abstract Operations are and that engines define them on their own and that we can't call them explicitly (though override them)
UPDATED Following is an excerpt from his Book:
He then says:
Upvotes: 0
Views: 419
Reputation: 665574
Primitive value 'a' will somewhere be boxed to Number object on fly for the sake of concatenation?
No. You missed that the [Symbol.toPrimitive]
property only applies to objects. You can see that the first operation ToPrimitive does is to check "If input
is an Object".
So this doesn't apply at all. No boxing happens, no methods are called. The primitive value 42
is immediately returned back from ToPrimitive. It is then passed to the ToString operation since the other operand of +
is a string.
Hint is passed only for explicit conversion?
You can easily check the spec for all places where ToPrimtive is called. In general, a hint will be passed, the only places I found where none is passed are the +
operator, the ==
/!=
operators when comparing an object to a primitive value, and weirdly when calling new Date
with a single argument (that is not a Date
object).
Will
OrdinaryToPrimitive
be called during coercion?
No. Coercion using the String()
function directly calls (except for symbols) the ToString operation which does, again, not use ToPrimitive (or OrdinaryToPrimitive) on non-objects. Instead, for numbers it directly dispatches to the number-to-string operation.
Upvotes: 2