JS: Property Key
Property Key
JavaScript Object is a collection of key and value pairs, each key and value pair is called a property.
- Property key must be string type or Symbol type.
- Property value can be any type.
Property String Key
String property keys example:
/* string property keys */ const jj = { "a": 1, b: 2 }; const ks = Object.keys(jj); console.log(typeof ks[0] === "string"); console.log(typeof ks[1] === "string");
If a key is not symbol or string, it is converted to string implicitly.
/* the second key 3 overrides the first, because it's converted to string */ const jj = { "3": "a", 3: "b" }; console.log(Object.values(jj).length === 1); console.log(JSON.stringify(Object.values(jj)) === `["b"]`);
When in a Object Literal Expression , the property names are converted to string, not evaluated as variable.
const xx = "bb"; const jj = { xx: 4 }; /* xx is converted to "xx", not evaluated as variable */ console.log(jj.xx === 4); console.log(jj.bb === undefined);
Computed Property Key in Object Literal Expression
To evaluate a variable as property key, put it inside a square bracket, like this:
obj = {[expr]:value}
Property Symbol Key
JavaScript, Property
- JS: Property Overview
- JS: Property Key
- JS: Property Dot Notation vs Bracket Notation
- JS: Create Property
- JS: Delete Property
- JS: Get Set Property
- JS: Check Property Existence
- JS: Access Property
- JS: List Properties
- JS: for-in Loop
- JS: Enumerable Property
- JS: Property Attributes
- JS: Property Descriptor
- JS: Getter Setter Properties