Exploiting valueOf() in Math Operations
You can leverage the valueOf() method to customize how an object is treated in mathematical operations. you can make objects behave like primitive values in arithmetic expressions and This can be useful when working with custom objects and you want them to interact seamlessly with the JavaScript’s built-in arithmetic operations.
Syntax:
const gfg = {
hours: 4,
minutes: 20,
valueOf() {
return this.hours * 50 + this.minutes;
}
};
Example: In this example, we are using the above-explained approach.
Javascript
const gfg = { hours: 4, minutes: 20, valueOf() { return this .hours * 50 + this .minutes; } }; const totalTimeInMinutes = gfg + 13; console.log(totalTimeInMinutes); |
233
Unleashing the Power of valueOf in JavaScript
In JavaScript, The valueOf() method is a fundamental method that allows objects to specify how they should be converted to primitive values. When an object is used in a context where a primitive value is expected JavaScript automatically calls the valueOf() method on the object to get its primitive representation.
Table of Content
- Customizing valueOf() for Basic Object
- Customizing valueOf() for Custom Class
- Exploiting valueOf() in Math Operations
We will explore all the above methods along with their basic implementation with the help of examples.