Skip to content
Related Articles

Related Articles

JavaScript Object.prototype.valueOf() Method

View Discussion
Improve Article
Save Article
  • Last Updated : 31 May, 2022
View Discussion
Improve Article
Save Article

In JavaScript , the Object.prototype.valueOf() method is used to return the primitive value of the specified object. Whenever a primitive value is required, JavaScript automatically invokes the valueOf() method. The valueOf() method is automatically inherited by every object in JavaScript. Every object overrides this method to return an appropriate primitive value. If no primitive value is present for this object, then JavaScript returns the object itself. We can override this method to convert any built-in object to a primitive value. In the case of Custom object types, we override this method to call a custom method.

If we are dealing with custom object types, we can use the following syntax to override valueOf() method for it :


ObjectType.prototype.valueOf = function() { 
    return CustomPrimitiveValue; 

In this syntax,

  • ObjectType: The custom object type created by the user.
  • CustomPrimitiveValue: The primitive value of the specified object.

Although the valueOf() method is automatically invoked in JavaScript, we can use the following syntax to invoke it ourselves :





    function myFunction() {
        // Creating a custom object
        // type ExType
        function ExType(n) {
            this.number = n;
        // A callback method overriding
        // the valueOf() method
        ExType.prototype.valueOf = function () {
            // Returned valued is 18+3 which is 21
            return this.number + 3;
        // Creating an object of ExType object type
        const object1 = new ExType(18);
        // Logs 21-12 which is 9
        console.log(object1 - 12);


In the above example, we tried to override the valueOf() method to return the primitive value as the actual number plus 3. Thus the primitive value returned after passing 18 as the argument was 21. As we tried to log primitive value minus 12, we got 21-12 which is 9 as our final answer. 

Supported Browsers:

  • Chrome 1 and above
  • Edge 12 and above
  • Firefox 1 and above
  • Internet Explorer 4 and above
  • Opera 3 and above
  • Safari 1 and above
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!