0

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

3
  • That's because window is an instance of Window... and example is an instance of Object. Commented Jul 24, 2017 at 15:32
  • As I understand it, Window is an Object. So, how did the marking change from Object to Window and how can I do that with my own Objects? Commented Jul 24, 2017 at 15:36
  • Please show us how you tried to use the symbol Commented Jul 24, 2017 at 15:41

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

@K.Rohde Browser compatibility says only IE doesn't support it yet
In Chrome, it worked. In Edge it displayed [object Object]. In IE it says, "''Symbol' is undefined". In Firefox it displayed Object.
@hutch90 Hmm, I guess. It's in the ECMAScript 2015 spec so Chrome's the only one that complies. It'll probably be supported in the future I suppose.
@AndrewLi Well, this works for me. I do my debugging in Chrome for the most part.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.