title: Why does console.dir output a stacktrace on an Error object?
body: <p>Today I encountered some behavior that really threw me for a loop while debugging, because at first I really didn't understand what I was looking at. After a lot of trial and error I came to understand that <code>console.dir</code> has some unusual behavior with <code>Error</code> objects, and I'd like to understand it better.</p>
  <p>If you open the Chrome developer console and run <code>console.dir({a: 1, b: 2})</code>, you'll see an expandable Object, like so:</p>
  <p><a href="https://i.stack.imgur.com/l7GkT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l7GkT.png" alt="chrome developer console" /></a></p>
  <p>Expanding the dropdown shows the properties <code>a</code> and <code>b</code>, plus their values, as expected. On a Promise, the results are similar, although notably the word <code>Object</code> is replaced by <code>Promise</code>:</p>
  <p><a href="https://i.stack.imgur.com/bDijr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bDijr.png" alt="enter image description here" /></a></p>
  <p>However, with an Error, the results are different:</p>
  <p><a href="https://i.stack.imgur.com/tbAyA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tbAyA.png" alt="enter image description here" /></a></p>
  <p>Notice now it prints a stacktrace. If you didn't know any better, you'd think you had just printed a string, and you might expect that dropdown arrow to show you more lines of the stacktrace. Of course, instead the dropdown shows you the properties on the object.</p>
  <p>But notice that <code>toString</code> gives something else, it gives the message but without the stack. If you expand the dropdown, what you see are these properties:</p>
  <p><a href="https://i.stack.imgur.com/N5pxY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/N5pxY.png" alt="enter image description here" /></a></p>
  <p>So it looks like <code>console.dir</code> is printing out the Error's <code>stack</code> property. But <em>why</em>? If <code>error.toString()</code> prints the <code>message</code> property, then why does <code>console.dir</code> instead show the value of the <code>stack</code> property, which of course only exists on Error objects? Is <code>console.dir</code> hard-coded to treat errors differently than other object classes?</p>
  <p>Likewise, <code>Promise().resolve().toString()</code> gives <code>[object Promise]</code> -- so where is <code>console.dir</code> getting the <code>Promise</code> string from when you run <code>console.dir</code> on a Promise? The behavior here is just unclear and I feel like I might learn something about the internals of <em>something</em> if I get a clearer understanding of this behavior.</p>