JavaScript: Object.prototype.valueOf

By Xah Lee. Date: . Last updated: .

obj.valueOf ()

Convert obj to a object type, return it.

[see this Binding]

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

[see 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 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 Object Constructor]

[see 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
JS in Depth
XAH  BUY NOW

JS in Depth

JS Obj Ref

DOM


JS Obj Ref

Object Object

prototype