Skip to content
Related Articles

Related Articles

Improve Article

JavaScript Object.prototype.valueOf() Method

  • Last Updated : 23 Apr, 2021

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 :

Syntax:

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 :

Syntax:

ObjectType.valueOf()

Example:

JavaScript




<script>
    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);
    }
      
    myFunction();
</script>

Output:

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. 

My Personal Notes arrow_drop_up
Recommended Articles
Page :