JS: Object.prototype.valueOf

By Xah Lee. Date: . Last updated: .
Object.prototype.valueOf

returns this (binding) it receives. e.g. myObj.valueOf() === myObj

If Type of this (binding) is not a object type, either return a error, or convert it to a object type, return it.

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.

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);
// testing use of Object.prototype.valueOf but with a primitive value as argument

const aa = Reflect.apply(Object.prototype.valueOf, true, []);
console.log(typeof aa === "object");
console.log(Boolean(aa));

const bb = Reflect.apply(Object.prototype.valueOf, 3, []);
console.log(typeof bb === "object");
console.log(Number(bb) === 3);

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