Node.js: How to get toString() to print object details
To get the toString()
method to print object details in Node.js, you can override the default implementation of the toString()
method for your custom objects.
Here’s an example of how you can achieve this:
class Person { constructor(name, age) { this.name = name; this.age = age; } toString() { return `Person { name: ${this.name}, age: ${this.age} }`; } } const person = new Person("John Doe", 30); console.log(person.toString());
In the above example, we define a Person
class with name
and age
properties. We override the toString()
method of the class to return a string representation of the object’s details. When we call toString()
on the person
object and log it to the console, it will print the custom string representation with the object’s details.
You can customize the toString()
method implementation to display any desired object details based on your specific requirements.
Leave a Comment