Summary: in this tutorial, you will learn the differences between the valueOf()
and toString()
methods of object in JavaScript.
The object has two similar methods:
valueOf()
method returns a primitive value of an object.toString()
method return the string representation of an object.
Note that a string is also a primitive value in JavaScript.
The valueOf()
and toString()
methods serve different purposes. The valueOf()
is usually called internally by JavaScript to convert an object to a primitive value.
For example, if you call the valueOf()
method on some built-in object like Date
, it’ll return a timestamp:
let d = new Date('2024-01-01 12:45:30');
console.log(d.valueOf());
Code language: JavaScript (javascript)
Output:
1704087930000
Code language: JavaScript (javascript)
In this example, the valueOf()
returns a timestamp that represents the Date
object.
The toString()
method will return a string that represents the Date
object:
let d = new Date('2024-01-01 12:45:30');
console.log(d.toString());
Code language: JavaScript (javascript)
Output:
Mon Jan 01 2024 12:45:30 GMT+0700 (Indochina Time)
Code language: JavaScript (javascript)
For most objects, the valueOf()
returns the objects themselves whereas the toString()
returns the [object Object]
.
For example:
const person = {
name: 'John Doe',
age: 30,
sayHi: () => {
console.log(`Hi`);
},
};
console.log(person.valueOf());
console.log(person.toString());
Code language: JavaScript (javascript)
Output:
{ name: 'John Doe', age: 30, sayHi: [Function: sayHi] }
[object Object]
Code language: JavaScript (javascript)
If you don’t want the default return value ([object Object]
) of the toString()
method, you can override it like this:
const person = {
name: 'John Doe',
age: 30,
sayHi: function () {
console.log(`Hi`);
},
toString: function () {
return `{name: "${this.name}", age: ${this.age}}`;
},
};
console.log(person.toString());
Code language: JavaScript (javascript)
Output:
{name: "John Doe", age: 30}
Code language: JavaScript (javascript)
Summary
valueOf()
method returns a primitive value, called internally by JavaScript, and often used in comparison and mathematical operations.toString()
method returns a string representation of an object and often used in string contexts.