JS: Object .prototype .valueOf

By Xah Lee. Date: . Last updated: .

Object.prototype.valueOf

Object.prototype.valueOf

return the value of this (binding) it receives. e.g. myObj.valueOf() === myObj

If type of this (binding) is not an object type, either throw an error, or convert it to an 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.assert(jj.valueOf() === jj);

Edge case. on primitive

// testing use of Object.prototype.valueOf but with a primitive value as argument

console.assert(
 typeof Reflect.apply(
  Object.prototype.valueOf,
  true,
  [],
 ) === "object",
);

console.assert(
 typeof Reflect.apply(
  Object.prototype.valueOf,
  3,
  [],
 ) === "object",
);

console.assert(
 typeof Reflect.apply(
  Object.prototype.valueOf,
  "abc",
  [],
 ) === "object",
);

Edge cases. on null

// Object.prototype.valueOf on null

try {
 Reflect.apply(Object.prototype.valueOf, null, []);
} catch (xerror) {
 console.log(xerror);
}

// TypeError: Cannot convert undefined or null to object