toString() will be called on it, and the key will be stringified to
If the above explanation did not make things obvious for you, or you in the mood for more probing, read on. Also, there is a way to actually use objects as key to values, read till the end.
You might be wondering, "Hey I have used objects as keys before!". Well, it sure might have looked like you used objects as keys, but it was not what you thought it was.
Run the following code:
You get the expected result. But not obvious to you, something is happening behind the scenes.
When you do
o[x] = 'Chuck Norris', the object
x is getting stringified to
[object Object]. And when you do
x is again getting stringified to
[object Object]. But since you getting expected result for
console.log(o[x]), you start to think you can actually use objects as keys.
Now get ready for the eye-opener. Run the following code:
There you are! You thought you were setting an object as key when actually you were setting values for the string key
[object Object]. See what happens when you try to use many objects as keys.
The object keys, after getting stringified, overwrite each other.
o[y] both are references to the string
o.x is a true references to key named
x of the object
How to use object as key to a value#
There is a way to use objects and keys to values, just not values of a conventional
Object. What you need is a
WeakMap is a key-value object, where the key must, in fact, be an object - just what you needed.
Here is an example of using objects as keys with a