JavaScript valueOf vs. toString Methods (original) (raw)

Skip to content

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:

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:

1704087930000Code 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

Was this tutorial helpful ?