Don P
Don P

Reputation: 63627

What is the type of the key when you set an object's key to be another object?

In JS, when you set an object's property key to be a some other object, what is the key? Is it the memory reference to the object as a string? Something else?

Example:

// Let's create some apples.
const apple1 = { tastes: 'great' };
const apple2 = { tastes: 'so-so' };

// Let's create an orchard to hold our apples, with constant time look-up for any individual apple, so we're not using an array. 
const orchard = {}

// And we add our first apple to the orchard. We want to keep track of some data.
orchard[apple1] = 1;
orchard[apple2] = 2;

At this point, console.logging the keys of orchard will show [object Object]. Console logging the typeof the keys will tell you that [object Object] is a string. But I can have multiple [object Object] keys, and they'll all be distinct.

Upvotes: 1

Views: 45

Answers (1)

Don P
Don P

Reputation: 63627

In JavaScript, all object keys are strings.

When setting a key, if the value is not a string, .toString() will be called on it.

Upvotes: 1

Related Questions