What is Object.valueOf() in Javascript?

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.

  • The valueOf() method is automatically invoked when the primitive value of the object is expected.
  • The method is inherited by the descendants of the object.
  • The objects override the method to return an appropriate primitive value.

Declaration

The valueOf() method is declared as follows:

obj.valueOf()
  • obj: The object whose primitive value is returned.

This method does not accept any parameters.

Overriding the valueOf() method

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.

Return value

The valueOf() method returns the primitive value of obj.

Note: If there is no primitive value, the object itself is returned.

Browser compatibility

The valueOf() method is supported by the following browsers:

  • Firefox
  • Google Chrome
  • Internet Explorer
  • Opera
  • Safari

Examples

Example 1

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.

Example 2

Consider another example in which the valueOf() method of a custom class is overridden:

//Custom object
function Student(Name,id) {
this.Name = Name;
this.id = id;
}
//Overriding valueOf() method
Student.prototype.valueOf = function ()
{
return this.id*10;
}
// calling valueOf() method
Student1 = 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

Copyright ©2024 Educative, Inc. All rights reserved