What is toString() in JS?

Overview

The toString method in JS is defined in the class Object. The toString method, when called on an instance of Object (or its derived instance), returns a text representation of the instance. The default implementation results in the following string:

'[object className]'

Here, className is the name of the class of the instance.

Note: The toString method can be overridden.

Example

The following example shows the result of invoking the toString method on an instance of Object.

let obj = new Object();
console.log(obj.toString());

The following example shows how to override the toString method:

class MyObj extends Object {
}
let obj1 = new MyObj();
console.log(obj1.toString());
MyObj.prototype.toString = () => 'This is [MyObj]';
let obj2 = new MyObj();
console.log(obj2.toString());

In the example above, the a new class MyObj is inherited from Object. Two instances of MyObj are stored inside obj1 and obj2, respectively. The former has the Object implementation for the toString method, and the latter has our custom implementation for the toString method. Therefore, the obj1.toString call results in [object Object] and the obj2.toString call results in This is [MyObj].

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved