The Object.valueOf()
method returns the primitive value of the specified object.
Example
// create a new Number object with value of 12
let num = new Number(12);
console.log(num);
// Output: [Number: 12]
console.log(num.valueOf());
// Output: 12
valueOf() Syntax
The syntax of the valueOf()
method is:
obj.valueOf()
Here, obj is an object whose primitive value we want to find.
valueOf() Parameters
The valueOf()
method does not take any parameters.
valueOf() Return Value
The valueOf()
method returns the primitive value of the specified object.
Notes:
- For objects of type
Object
, there is no primitive value, so thevalueOf()
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: Using Built-in valueOf() Method
// create a Number object
var num = new Number(12);
console.log(num.valueOf() + 8);
// Output: 20
console.log(num + 8);
// Output: 20
In the above example, we create a Number
object called num with a value of 12.
When we call the valueOf()
method on num, it returns the primitive value of 12, which is then added to 8 to produce an output of 20.
Similarly, when we add num to 8, the valueOf()
method is called implicitly, and the expression is evaluated to produce an output of 20.
Example 2: Create a Custom valueOf() Method
// create a constructor function
function customNum(n) {
this.number = n;
}
// create a custom valueOf() function
customNum.prototype.valueOf = function () {
return this.number;
};
// create num1 object from customNum() constructor function
var num1 = new customNum(2);
console.log(num1 + 3);
// Output: 5
In the above example, we have created a custom valueOf()
method which overrides the built-in valueOf()
method of JavaScript. This method returns the value from the number property from the CustomNum()
function.
The valueOf()
method is implicitly called when num1 is added to 3 and we get result 5.
Example 3: valueOf() Method With Unary + Operator
// create a number with the value of 5
const num = 5;
// use + operator in front of the string operand
console.log(+"5" + num);
// Output: 10
console.log(+[1] + num);
// Output: 6
console.log(+true + num);
// Output: 6
console.log(+false + num);
// Output: 5
console.log(+undefined + num);
// Output: NaN
console.log(+null + num);
// Output: 5
In the above example, the +
operator first calls the built-in valueOf()
method on the operand to get a primitive value. The resulting primitive value is then converted to a number using the unary plus operator +
.
Note: If the valueOf()
method does not return a primitive value, the toString()
method is called instead, and the resulting string is converted to a number.
Recommended Reading: