JS Built-ins
← Object149 / 150
ObjectvalueOfintermediate

valueOf() β€” custom valueOf override

πŸ“– 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() β€” custom override

You can override valueOf() in your own objects to control how they convert to primitives, especially in arithmetic operations.

Challenge: Create an object with a custom valueOf() that returns a specific number.

πŸ’‘ Hints (1)
  • β€’ Override valueOf to control how an object converts to a primitive in arithmetic or comparisons