I have recently started learning more about coercion in Js and I have been going through the ECMAScript documentation for knowing more about it and how different cases are handled in Js. While doing I encountered the following statement
10-{"a":10,valueOf(){return 8;}}
>2
This is the problem along with the output from my browser console can you help me decode how the result comes step by step I did try the simpler version of the same problem which included only the {"a":10} part and thus
10-{"a":10}
>NaN
understood how the Nan result is obtained but didn't get the first stated problem where the result is 2 Also, one more thing the function valueOf() will return 8 but that will be inside the object's braces isn't it like {"a":10,8}, or is something else happening? So help me understand why Is result 2?
10-{"a":10,valueOf(){return 8;}}is doing10minus an object, where the object has a property calledawith the value10(which is irrelevant; it's not used), and avalueOfmethod that returns8(which is very relevant :-) ).The subtraction operator requires that its operands be numbers. When one of its operands isn't a number, it uses the abstract ToNumber operation on it to convert it to number. For an object (as in your example), ToNumber uses ToPrimitive saying its preferred type is "number". In the case of an ordinary object (such as yours), that ends up doing OrdinaryToPrimitive. OrdinaryToPrimitive looks to see if the object has certain methods that can be used to get a primitive from the object. When the preferred type is "number," the first method OrdinaryToPrimitive tries is
valueOf. So that method of your object is called, returns8, and10-8is performed (resulting in2).Here's that code written more clearly, and without any implicit type conversion: