JS Built-ins
← Object146 / 150
ObjectvalueOfbeginner

valueOf() β€” plain object

πŸ“– 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.

Object.prototype.valueOf()

obj.valueOf() returns the primitive value of the specified object. For plain objects, it returns the object itself (since there is no primitive equivalent).

Challenge: Implement getValueOf(obj) that returns the valueOf result.

πŸ’‘ Hints (1)
  • β€’ For plain objects, valueOf returns the object itself; subclasses override it to return primitives