JavaScript: Object.prototype.valueOf

By Xah Lee. Date: . Last updated: .

Object.prototype.valueOf ()

Convert the value of thisBinding to a object type, return it.

〔►see JavaScript: “this” Binding

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

〔►see JavaScript: Data Types

It's usually called in this form:

The purpose is to convert a primitive value arg to a object version of arg.

〔►see JavaScript: 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 JavaScript: Object Constructor

〔►see JavaScript: Primitive Value

Here's a table showing the conversion:

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

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

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

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

Error example:

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


ECMAScript 2015 §Fundamental Objects#sec-object.prototype.valueof

Object and Inheritance Topic

  1. JavaScript: Object System Overview
  2. JavaScript: What's Object?
  3. JavaScript: Prototype and Inheritance
  4. JavaScript: Create Object
  5. JavaScript: Object Literal Expression
  6. JavaScript: Find Object's Prototype
  7. JavaScript: How to Create Object with Parent X?
  8. JavaScript: Prevent Adding Property
  9. JavaScript: Determine Type of Object
  10. JavaScript: Primitive Value Object Wrapper
  11. JavaScript: Clone, Deep Copy Object/Array
  12. JavaScript: Test Equality of Objects

  1. JavaScript: Object Object
  2. JavaScript: Object.prototype
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.