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:

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 is a table showing the conversion:

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

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

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

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

Error example:

console.log( ( null )  );
// TypeError: Cannot convert undefined or null to object
JavaScript in Depth

JS Obj Reference

Object Object