valueOf()  Object  instance method JS Home  <<  JS Reference  <<  Object  <<  valueOf()


Returns the primitive value of an object.

  • Automatically invoked when an object is called and a primitive value is expected.
  • The Object.valueOf() method is inherited by all Object descendants.
  • Unless overridden by a custom object valueOf() returns [object Object].


Signature Description
anObject.valueOf()Returns the primitive value of an object.




The code below creates an object and displays it.

// Create an object.
anObject = new Object();

alert(anObject.valueOf() + ' anObject is an instance of Object.');

Press the button below to action the above code:

Overriding The Object.valueOf() Method

As you can see when pressing the above button the default for valueOf() on an objectType of Object returns [object Object]. If you want something meaningful returned for your object, you need to override the Object.valueOf() method.

The code below creates a custom object type function and overrides the Object.valueOf() method. We then create and display a string primitive which will use our custom valueOf() method.

// Define a custom object type function.
function HomeOwner(firstName,lastName) {  

// Define a custom override function for valueOf().
HomeOwner.prototype.valueOf = function HomeOwnervalueOf() {  
  var primValue = 'Home Owner';  
  return primValue;  

// Create and print a HomeOwner primitive.
owner = new HomeOwner('Barney','Magrew');  

Press the button below to action the above code:

Related Tutorials

JavaScript Basic Tutorials - Lesson 7 - Objects