How Javascript convert an object to a primitive using OPCA
Using valueOf
- Used if method valueOf() exists.
- If valueOf() returns a primitive, the object is converted to this value
- But most of the native objects when calling the valueOf() method returns the object itself. So the toString() method is used more often
Using toString()
- Used if method toString() exists.
- If toString() returns a primitive, the object is converted to this value
- Date object use toString() instantly instead of valueOf
- The plain JavaScript object, {} or new Object(), usually is converted to "[object Object]".
- An array is converted to by joining it’s elements with "," separator.
- For example [1, 3, "four"] is converted to "1,3,four"