hutch90 hutch90 - 3 years ago 116
Javascript Question

Custom string instead of "Object" in console.log

For convenience while debugging, I think it would be nice to print some custom string, rather than the default

Object
that appears when logging an object to the console.

In the following example, see how an object called
example
is marked by
Object
when it is logged to the console, whereas
window
is marked by
Window
when it is logged to the console. I guessed that the
__proto__["Symbol(Symbol.toStringTag)"]
property might be the way to go, since
window
's is set to
Window
. That didn't work, but maybe I'm just using it wrong.

enter image description here

Answer Source

That's because you're using the Symbol wrong -- you were on the right track. Symbol.toStringTag is a special well-known Symbol used by Object#toString to give you the console output, specifically the tag you're after. You can't wrap it in a string as you've done, or else you'll be literally setting the "Symbol.toStringTag" property, not the actual Symbol:

const example = {
  key: "value"
};

example.__proto__["Symbol.toStringTag"] = "Example";
console.log(example); //You set the literal "Symbol.toStringTag" property -- wrong

Instead, don't wrap it in quotes and actually set the Symbol:

const example = {
  key: "value"
};

example.__proto__[Symbol.toStringTag] = "Example";
console.log(example);

Which produces (on Chrome):

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download