Open In App

JavaScript Object.prototype.valueOf() Method

Improve
Improve
Like Article
Like
Save
Share
Report

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: In this 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.

JavaScript




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();


Output

9

Example:  In this example, the person object has properties of name and age. toString() returns the name and age, and valueOf() returns the age as the primitive value.

Javascript




const person = {
    name: "John",
    age: 30,
    toString() {
        return `Name: ${this.name}, Age: ${this.age}`;
    },
    valueOf() {
        return this.age;
    }
};
 
console.log(person.toString());
// Output: "Name: John, Age: 30"
console.log(person.valueOf());
// Output: 30


Output

Name: John, Age: 30
30

Supported Browsers:

  • Chrome 1 and above
  • Edge 12 and above
  • Firefox 1 and above
  • Opera 3 and above
  • Safari 1 and above


Last Updated : 10 Aug, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads