DEV Community

Berra
Berra

Posted on

1

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.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more