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.
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.
You can simply define a toString() method for the object or class.
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]"
class Foo {
toString() {
return 'Foo';
}
}
const foo = new Foo();
foo + '';
`Foo: ${foo}`;
foo.toString();
const foo = {};
foo + ''; // Noncompliant - evaluates to "[object Object]"
`Foo: ${foo}`; // Noncompliant - evaluates to "Foo: [object Object]"
foo.toString(); // Noncompliant - evaluates to "[object Object]"
const foo = {
toString: () => {
return 'Foo';
}
}
foo + '';
`Foo: ${foo}`;
foo.toString();
Object.prototype.toString()