Property names

The keys that are used to add properties to objects (the property names) are internally stored as strings. However, when using the object literal syntax, you can declare the keys as regular identifiers (that is, anything you could use as a variable name), number literals, or string literals:

const object = {
foo: 123, // Using an identifier as the key
"baz": 123, // Using a String literal as the key
123: 123 // Using a Number literal as the key
};

It's preferable to use identifiers where possible as this helpfully restricts you to using key names that can easily be accessed as properties. If you use a string literal that is not also a valid identifier, then you'll have to use square-bracket notation to access it, which can be burdensome:

const data = {
hobbies: ['tennis', 'kayaking'],
'my hobbies': ['tennis', 'kayaking']
};

data.hobbies; // Easy
data['my hobbies']; // Burdensome

You can also use computed property names (delimited by square brackets) to add dynamically named items to an object literal:

const data = {
['item' + (1 + 2)]: 'foo'
};

data; // => { item3: "foo" }
data.item3; // => "foo"

As we mentioned previously, all non-primitives in JavaScript are technically objects. What else makes something an object, though? Objects allow us to assign arbitrary values to them as properties, which is something primitives are not capable of. Beyond this characteristic, the definition of an object in JavaScript is left invitingly generic. We can wield objects in many different ways to suit the code we're writing. Many languages will provide language constructs for dictionaries or hashmaps. In JavaScript, we can use objects to fulfill most of these needs. When we need to use store a key-value pair where the key is something other than a string, it's common to provide a string representation of that value via the object's toString method:

const me = {
name: 'James',
location: 'England',
toString() {
return [this.name, this.location].join(', ')
}
};

me.toString(); // => "James, England"
String(me); // => "James, England"

This will be called internally when the object is put in a context where it is coerced to a string, such as when accessing or assigning via square-bracket notation:

const peopleInEurope = {};

peopleInEurope[me] = true;
Object.keys(peopleInEurope); // => ["James, England"]
peopleInEurope[me]; // => true

This has historically been used to allow the implementation of data structures where the key is effectively non-primitive (even though objects technically store property names as strings). Nowadays, however, using Map or WeakMap is preferred.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.104.183