This content originally appeared on DEV Community and was authored by Evan Charalampidis
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.
Github: @imevanc
Twitter: @imevancc
This content originally appeared on DEV Community and was authored by Evan Charalampidis