YDKJS: this & Object Prototypes - Trouble understanding [object Object]

Under the section ‘Contents’ of the book, at one point the following code is used to assign a value to an object property:

myObject[myObject] = “baz”;

The property is then accessed further down using the following:

myObject["[object Object]"]; // “baz”

I’ve already looked into how and why [object Object] is sometimes outputted by a function, but I am struggling to understand how one can use it to access myObject[myObject].

I tried logging myObject[“myObject”] to the console and noticed that it returns ‘undefined’ but I would like to know why the way the property was accessed in the book works whereas the latter returns ‘undefined’.

Thanks in advance.

When we see [object Object], that’s just a string with no special meaning. So, by using it for object assignment, you’re saying that your object myObject has a field called "[object Object]". It may make more sense in object literal format:

myObject = {
    "[object Object]": "baz"
}
2 Likes

Thank you very much for the help PortableStick. After staring at your answer for long enough and playing around with the code used in the book, I believe I was able to grasp the concept.

The problem was that I was under the impression that “[object Object]” was specific to myObject and would always output “baz”. There was, however, nothing to support the relationship I had perceived to exist between the two, which is why I was having some trouble.

After creating an arbitrary object, testObject, and assigning “bat” to it and then looking at the value assigned to “[object Object]” again, I found that the value of “[object Object]” was now “bat”.

Thus, I was able to conclude that there was no special relationship between the property “[object Object]” and myObject, but, rather, any object that was converted to a string via .toString() would become “[object Object]”.

The following is what I did to make sense of what was going on:
var myObject = { };
var testObject = { };

myObject[true] = “foo”;
myObject[3] = “bar”;
myObject[myObject] = “baz”;
myObject[testObject] = “bat”;

myObject[“true”]; // “foo"
myObject[“3”]; // “bar"
myObject[”[object Object]”]; // “bat” as opposed to “baz”