DEV Community

Discussion on: Understanding valueOf() and toString() in JavaScript

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

The reality is slightly more complex... this is the default toPrimitive algorithm that JS uses:

toPrimitive

However, if an object has a method named with the well-known symbol Symbol.toPrimitive - then this will be run instead, allowing you to override the default behaviour shown above.

Collapse
 
jonrandy profile image
Jon Randy 🎖️

An example of using Symbol.toPrimitive can be found in my experiment to add a range syntax to numbers:

Collapse
 
tapuchandramojumder profile image
tapuchandramojumder

nice article. I am totally agree with you. It's really hard to understand