DEV Community

Cover image for Why JavaScript Says "[object Object]" and Not Just "[object]" 🤔
Evan Charalampidis
Evan Charalampidis

Posted on

Why JavaScript Says "[object Object]" and Not Just "[object]" 🤔

If you’ve been working with JavaScript, chances are you’ve seen the mysterious "[object Object]" in your console at some point. But why does JavaScript say that? Why not just "[object]"? Let's demystify this little quirk! 🔍

The "Object" Inside the Object 🤯

The reason JavaScript outputs "[object Object]" instead of just "[object]" comes down to the many different types of objects in JavaScript. In other words, not all objects are created equal! Let's take a closer look:

  • Function Objects When you stringify a function in JavaScript, you get [object Function].
stringify(function () {}) // [object Function]
Enter fullscreen mode Exit fullscreen mode
  • Array Objects Arrays are also objects in JavaScript, but they’re a special type. When stringified, they return [object Array].
stringify([]) // [object Array]
Enter fullscreen mode Exit fullscreen mode
  • RegExp Objects Regular expressions? Yup, they’re objects too. Stringify one, and you’ll see [object RegExp].
stringify(/x/) // [object RegExp]
Enter fullscreen mode Exit fullscreen mode
  • Date Objects Dates in JavaScript are, you guessed it, objects! When stringified, they return [object Date].
stringify(new Date()) // [object Date]
Enter fullscreen mode Exit fullscreen mode
  • Object Objects Finally, we get to the classic Object object. When you stringify an object created using {}, you get [object Object].
stringify({}) // [object Object]
Enter fullscreen mode Exit fullscreen mode

Why [object Object]? 🤷‍♂️

Now, here’s the interesting part! You might wonder: Why does it say [object Object] specifically?

That’s because the constructor function behind these simple {} objects is called Object (with a capital "O"). The lowercase "object" part refers to the structural nature of the entity—it’s a "thingy" that can hold properties and methods. But in this case, JavaScript is telling you that it's an instance of the Object class.

What Are We Usually Referring to as "Objects"? 🧐

When JavaScript developers talk about "objects," they’re typically referring to Object objects (those created using {}), rather than other special types like functions, arrays, or dates.

To illustrate this more clearly, you can create a simple stringify function that reveals what kind of object you’re dealing with. Here’s how it works:

function stringify(x) {
  console.log(Object.prototype.toString.call(x));
}
Enter fullscreen mode Exit fullscreen mode

This function taps into JavaScript’s built-in Object.prototype.toString() method, which reveals the actual type of object in the form [object Type].

Stay tuned, and happy coding! 👩‍💻👨‍💻
Follow me on GitHub for more updates and check out my other articles on Dev.to.

Github: @imevanc
Twitter: @imevancc

Top comments (0)