JS Tip of the Day: Symbol.toStringTag

Symbol.toStringTag
Version: ES2015
Level: Intermediate

You may recognize this iconic string: [object Object]. This will sometimes sneak into your output accidentally as its the default “toString” representation for basic objects in JavaScript.

let basic = { data: 'GOTO 1' };
console.log(`The data I faxed was ${basic}.`);
// The data I faxed was [object Object].

If an object type doesn’t have its own custom toString implementation, the toString method from the Object type will get inherited and used when converting an object into a string. Its this version of toString which produces the output seen above. It follows the format "[object ${tag}]" where the tag value is the object’s “toString tag”.

The toString tag of an object can be determined a couple different ways, but the most direct way is to have a Symbol.toStringTag property in the object. If available, the value of this property is used by the default Object toString for it’s value of tag. If not, the default of “Object” is used.

let basic = { data: 'GOTO 1', [Symbol.toStringTag]: 'BASIC' };
console.log(`The data I faxed was ${basic}.`);
// The data I faxed was [object BASIC].

The value of the Symbol.toStringTag property can be any string and can be in the object itself or inherited. Of course, I doubt our example in particular wants any version of the default toString, so it would be better off implementing its own custom version, skipping the need for a toString tag entirely.

let basic = {
    data: 'GOTO 1',
    toString () {
        return `"${this.data}"`;
    }
};
console.log(`The data I faxed was ${basic}.`);
// The data I faxed was "GOTO 1".

More info: