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]
- Array Objects Arrays are also objects in JavaScript, but theyâre a special type. When stringified, they return [object Array].
stringify([]) // [object Array]
- RegExp Objects Regular expressions? Yup, theyâre objects too. Stringify one, and youâll see [object RegExp].
stringify(/x/) // [object RegExp]
- Date Objects Dates in JavaScript are, you guessed it, objects! When stringified, they return [object Date].
stringify(new Date()) // [object Date]
- Object Objects Finally, we get to the classic Object object. When you stringify an object created using {}, you get [object Object].
stringify({}) // [object Object]
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));
}
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.