JS Built-ins
← Object150 / 150
ObjectvalueOfintermediate

valueOf() β€” implicit conversion in arithmetic

πŸ“– Usage Example
// Retrieve the primitive value of an object
const n = new Number(42)
n.valueOf()   // β†’ 42
const obj = { valueOf() { return 10 } }
obj + 5       // β†’ 15

Use valueOf() to retrieve the underlying primitive value of an object; JavaScript calls it automatically in numeric contexts.

valueOf() β€” implicit type coercion

When an object is used in arithmetic (like +, -, *), JavaScript automatically calls valueOf() to convert it to a primitive. You can leverage this by overriding valueOf().

Challenge: Show how a custom valueOf is implicitly called in arithmetic.

πŸ’‘ Hints (1)
  • β€’ JavaScript uses valueOf for type coercion in arithmetic and comparison contexts