JS: Object.prototype.valueOf

By Xah Lee. Date: . Last updated: .

Object.prototype.valueOf ()

Convert the value of thisBinding 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: Data 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
var obj = {};
console.log ( obj.valueOf() === obj ); // true

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

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

var x = Object.prototype.valueOf.call ( "abc" );
console.log ( x ); // [String: 'abc']
console.log ( typeof x === "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

Object and Inheritance Topic

  1. JS: Object System Overview
  2. JS: What's Object?
  3. JS: Prototype and Inheritance
  4. JS: Create Object
  5. JS: Object Literal Expression
  6. JS: Find Object's Prototype
  7. JS: Set Object's Prototype
  8. JS: How to Create Object with Parent X?
  9. JS: Prevent Adding Property
  10. JS: Determine Type of Object
  11. JS: Primitive Value Object Wrapper
  12. JS: Clone, Deep Copy Object/Array
  13. JS: Test Equality of Objects

  1. JS: Object Object
  2. JS: Object.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon