JS: Property Key

By Xah Lee. Date: . Last updated: .

Property Key

JavaScript Object is a collection of key and value pairs, each key and value pair is called a property.

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}

[see JS: ES2015 Object Literal Expression Extensions]

Property Symbol Key

Symbol Tutorial

JavaScript, Property

BUY Ξ£JS JavaScript in Depth