The syntax of the valueOf()
method is:
obj.valueOf()
Here, obj
is an object.
valueOf() Parameters
The valueOf()
method does not take any parameters.
Return value from valueOf()
- Returns the primitive value of the specified object.
Notes:
- For objects of type
Object
, there is no primitive value, sovalueOf()
method simply returns the object itself. - For objects of type
Number
,Boolean
, orString
, however,valueOf()
returns the primitive value represented by the corresponding object.
Example 1: Custom valueOf()
function customNum(n, fact) {
this.number = n;
this.fact = fact;
}
customNum.prototype.valueOf = function () {
return this.number;
};
var num1 = new customNum(2, "First Prime Number");
console.log(num1 + 3); // 5
Output
5
Example 2: Using built-in valueOf()
// built-in valueOf()
const num = 5;
// string.toString() changes string to number
console.log(+"5" + num); // 10
console.log(+[1] + num); // 6
console.log(+true + num); // 6
console.log(+false + num); // 5
console.log(+undefined + num); // NaN
console.log(+null + num); // 5
Output
10 6 6 5 NaN 5
Recommended Reading: JavaScript Object toString()