Useful blog

[JS] Object’s original value conversion

Before starting the article, we first need to understand what Symbol. toPrimitive is.
Symbol. toPrimitive is a special type of Symbol value that can serve as an object’s property key to define the behavior of an object when converted to its original value. When an object is converted to its original value, the JavaScript engine attempts to call the Symbol. toPrimitive method on the object to determine the result of the conversion. For example, when an object {[Symbol. toPrimitive]: ()=>1} is converted to its original value, it becomes 1.
It should be noted that Symbol.toPrimitive must be a function, otherwise an error will be reported.
The Symbol.toPrimitive method has one parameter, which is the target type of the conversion, and can be one of the following three strings:
“Number”: Refers to converting an object to a numerical type.
“String”: represents converting an object to a string type.
“Default”: Refers to converting according to the requirements in the context, used in scenarios of implicit type conversion and default conversion types.
Example:

Convert objects to numbers

When converting an object to a number, the Symbol. toPrimitive method is first called. If the Symbol. toPrimitive method does not exist or returns a non JS original value (the rule of omitting the original value below), the value Of method is called. If the value Of method does not exist, the toString method is called. If the toString method also does not exist, the conversion will report an error: TypeError: Cannot convert object to primitive value, The meaning is that the object cannot be converted to its original value.

Overall, the order of calls is: Symbol. toPrimitive ->valueOf ->toString.

Convert objects to strings

In general, we use String() or xx. toString() to convert objects to strings, but there are some differences between them. The String() method will first attempt to call the Symbol. toPrimitive method in the object; If Symbol.toPrimitive does not exist, an attempt will be made to call the toString method in the object.

The order of converting objects to strings using String() is: Symbol. toPrimitive ->toString. Yes, valueOf will not be called.

Convert objects to Boolean values


The rule for converting objects to Boolean values is quite special, and it is true regardless of whether there is a Symbol. toPrimitive, valueOf, or toString in the object

Convert objects to large integers (BigInt)


The rules for converting objects to BigInt and number are similar, both in the order of Symbol. toPrimitive ->valueOf ->toString

Exit mobile version