JavaScript: Object.prototype.valueOf

By Xah Lee. Date: . Last updated: .
Reflect.apply(Object.prototype.valueOf, x, [])
Convert x to a object type, return it.

The x is usually a Primitive Value.

If Type of x is object, returns x itself.

It's usually called in one of the following form:

  • Object.prototype.valueOf.call(x)
  • Reflect.apply(Object.prototype.valueOf, x, [])

[see Function Call, Apply, Bind]

Here is a table showing the conversion:

ValueResult
undefinedthrow TypeError
nullthrow TypeError
true or falseboolean object
numbernumber object
stringstring object
symbolsymbol object
objectobject
const jj = {};
console.log(jj.valueOf() === jj);

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

const x2 = Object.prototype.valueOf.call(3);
console.log(typeof x2 === "object");
console.log(Number(x2) === 3);

const x3 = Object.prototype.valueOf.call("abc");
console.log(typeof x3 === "object");
console.log(String(x3) === "abc");
// Error example
// console.log(Object.prototype.valueOf.call(null));
// TypeError: Cannot convert undefined or null to object

It has similar behavior as the Object Constructor 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.

BUY ΣJS JavaScript in Depth