When calling toString() or coercing into a string an object that doesn’t implement its own toString method, it returns [object Object] which is often not what was intended.

Why is this an issue?

When using an object in a string context, a developer wants to get the string representation of the state of an object, so obtaining [object Object] is probably not the intended behaviour and might even denote a bug.

How to fix it

You can simply define a toString() method for the object or class.

Code examples

Noncompliant code example

class Foo {};
const foo = new Foo();

foo + ''; // Noncompliant - evaluates to "[object Object]"
`Foo: ${foo}`; // Noncompliant - evaluates to "Foo: [object Object]"
foo.toString(); // Noncompliant - evaluates to "[object Object]"

Compliant solution

class Foo {
  toString() {
    return 'Foo';
  }
}
const foo = new Foo();

foo + '';
`Foo: ${foo}`;
foo.toString();

Noncompliant code example

const foo = {};
foo + ''; // Noncompliant - evaluates to "[object Object]"
`Foo: ${foo}`; // Noncompliant - evaluates to "Foo: [object Object]"
foo.toString(); // Noncompliant - evaluates to "[object Object]"

Compliant solution

const foo = {
  toString: () => {
    return 'Foo';
  }
}
foo + '';
`Foo: ${foo}`;
foo.toString();

Resources

Documentation