DEV Community

Berra
Berra

Posted on

Create a custom toString method.

Do you get really angry if you see [object Object] in your browser. Well, this is the fix you might not need.

If an object has a toString method on itself that method will be called whenever javascript is trying to make the object to a string. Cool, right?

For example to output the name in a cool way at all times create a function that returns an object with your custom toString method.

function createPerson(firstName, lastName) {
  function toString() {
    return `${this.lastName}, ${this.firstName} ${this.lastName}`;
  }

  return {
    firstName,
    lastName,
    toString
  }
}
Enter fullscreen mode Exit fullscreen mode

Now

JD = createPerson("John", "Doe");
let html = `<q>My name is: ${JD}.</q>`;
document.body.innerHTML = html;
Enter fullscreen mode Exit fullscreen mode

Of course you could also do this if you feel like it:

Object.prototype.toString = function toString() {
  throw new Error("Do not parse ME as a string!");
}
Enter fullscreen mode Exit fullscreen mode

I hope you find this useful or interesting.

Top comments (0)