The Object.valueOf()
is a method that returns the primitive value of an object. The primitive value is the value of type undefined
, null
, boolean
, number
, string
, or symbol
.
valueOf()
method is automatically invoked when the primitive value of the object is expected.The valueOf()
method is declared as follows:
obj.valueOf()
obj
: The object whose primitive value is returned.This method does not accept any parameters.
The valueOf()
method of a custom object is overridden as follows:
obj.prototype.valueOf =function()
{
return primValue;
};
obj
: The object whose primitive value is returned.primValue
: The custom primitive value to return.The valueOf()
method returns the primitive value of obj
.
Note: If there is no primitive value, the object itself is returned.
The valueOf()
method is supported by the following browsers:
Consider the code snippet below, which demonstrates the use of the valueOf()
method:
var Student = { Name: 'Ali', RollNo: '234' }console.log(Student.valueOf())
The valueOf()
method of the object is not overridden, so the object itself is returned.
Consider another example in which the valueOf()
method of a custom class is overridden:
//Custom objectfunction Student(Name,id) {this.Name = Name;this.id = id;}//Overriding valueOf() methodStudent.prototype.valueOf = function (){return this.id*10;}// calling valueOf() methodStudent1 = new Student('Ali',2);console.log(Student1.valueOf());
The valueOf()
method of the object is overridden such that the property id
of the object Student
is multiplied by 10
and returned as the primitive value of Student
by the valueOf()
method.
Free Resources