Here’s the link to that section.
In the last code snippet in this section:
var myObject = { };
myObject[true] = "foo";
myObject[3] = "bar";
myObject[myObject] = "baz";
myObject["true"]; // "foo"
myObject["3"]; // "bar"
myObject["[object Object]"]; // "baz"
Can someone explain to me how this line myObject["[object Object]"];
value equals baz
?
Bracket notation only accepts string values. When you do
myObject[myObject] = 'baz'
the myObject
in the brackets is coerced to a string, which happen to be '[object Object]'
. That’s why you got the same 'baz'
when you do myObject['[object Object]']
.
1 Like
Why it didn’t coerce it to "myObject"
?
That’s how the spec for the language defined coercing objects to strings by default. You can define your own way of coercing objects to strings.
1 Like