Sadiq
Sadiq

Reputation: 838

ToPrimitive VS OrdinaryToPrimitive

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) :

  1. Primitive value 'a' will somewhere be boxed to Number object on fly for the sake of concatenation?
  2. Hint passed in Line 2 will be default(i.e. Number) but in line 3, it will be string. Hint is passed only for explicit conversion?
  3. Will OrdinaryToPrimitive be called during coercion? Since Number.prototype doesn't contain method, Symbol.toPrimitive (Because Reflect.ownKeys(Array.prototype) doesn't return Symbol.toPrimitive), hence exoticToPrim would be undefined. And even for other objects (such as Array.prototype doesn't contain this method) so it seems like, as per spec 7.1.1 1a and 1b are executed only for custom exotic objects (the one which overrides Symbol.Primitive).

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:

enter image description here

He then says:

enter image description here

Upvotes: 0

Views: 419

Answers (1)

Bergi
Bergi

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

Related Questions