JS Spec debunking for toPrimitive on an object

JS Spec debunking for toPrimitive on an object


2 min read

Let's say we have an object by the variable name of obj and ToPrimitive abstract method has been called on it implicitly. This implicit call happens when you do a comparison like this - obj == 5 || false == obj etc. Basically when one of the operands in a == comparison is a primitive and other one is an object.

For our case let's say we have this comparison - [] == 9.

The following is an attempt to clarify the working of toPrimitive as per spec :-

  1. First we check whether typeof [] is object or not which it is in our case.
  2. Now we check for hint which will be default here.
  3. Then we see if toPrimitive has been explicitly defined or not on the concerned object. Since it hasn't been for [], then exoticToPrim will be undefined.
  4. Now OrdinaryToPrimitive([],number) will be invoked for default hint.
  5. Since in our case hint is number, following will happen:-
    • Let methodNames be like a list of ["valueOf","toString"].
    • Loop over these methods and first check if method is callable (which both of the stated are)
    • Check if result of [].method() is a primitive or not.
    • [].valueOf() = [] but [].toString() is "" which being a primitive will be chosen.
  6. So updated comparison will be "" == 9.

I am no expert in specs debunking but I think this is what is happening. Feel free to comment and correct me if there is any wrong conclusion derived here.