JS: Object.prototype.valueOf

By Xah Lee. Date: . Last updated: .

obj.valueOf ()

Convert obj to a object type, return it.

[see JS: “this” Binding]

For example, in obj.valueOf (), if type of obj is type object, returns obj itself.

[see JS: Value Types]

It's usually called in this form:

Object.prototype.valueOf.call(arg)

The purpose is to convert a primitive value arg to a object version of arg.

[see JS: Function Call, Apply, Bind]

It has similar behavior as Object(arg), except in the Object(arg) case, if arg is null or undefined, it creates a empty object, while in the valueOf() case, it throws TypeError.

[see JS: Object Constructor]

[see JS: Primitive Value]

Here's a table showing the conversion:

ValueResult
undefinedthrow TypeError
nullthrow TypeError
booleanboolean object
numbernumber object
stringstring object
symbolsymbol object
objectobject
const obj = {};
console.log ( obj.valueOf() === obj ); // true

const x1 = Object.prototype.valueOf.call ( true );
console.log ( x1 ); // [Boolean: true]
console.log ( typeof x1 === "object" ); // true

const x2 = Object.prototype.valueOf.call ( 3 );
console.log ( x2 ); // [Number: 3]
console.log ( typeof x2 === "object" ); // true

const x3 = Object.prototype.valueOf.call ( "abc" );
console.log ( x3 ); // [String: 'abc']
console.log ( typeof x3 === "object" ); // true

Error example:

console.log ( Object.prototype.valueOf.call ( null )  );
// TypeError: Cannot convert undefined or null to object

Reference

ECMAScript 2015 §Fundamental Objects#sec-object.prototype.valueof

JS Object and Inheritance

  1. Object Overview
  2. Object Type
  3. Prototype and Inheritance
  4. Create Object
  5. Object Literal Expression
  6. Create Object with Parent X
  7. Get/Set Prototype
  8. Prevent Adding Property
  9. Determine Type of Object
  10. Clone Object
  11. Test Object Equality
  12. Add Method to Prototype
  13. Object Object
  14. Object.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog