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.

, , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Related posts

Latest posts

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Node.js: How to get toString() to print object details" />

Please disable your adblocker or whitelist this site!

How to whitelist website on AdBlocker?

How to whitelist website on AdBlocker?

  1. 1 Click on the AdBlock Plus icon on the top right corner of your browser
  2. 2 Click on "Enabled on this site" from the AdBlock Plus option
  3. 3 Refresh the page and start browsing the site