JavaScript: Property Key

By Xah Lee. Date: . Last updated: .

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 obj = { "a": 1, b: 2 };

const ks = Object.keys(obj);

console.log(typeof ks[0] === "string"); // true
console.log(typeof ks[1] === "string"); // true

If a key is not symbol or string, it is converted to string implicitly.

console.log({ "3": 4, 3: 7 }); // { '3': 7 }
// the second key 3 overrides the first, because it's converted to string

When in a literal expression for object {…}, the property names are converted to string, not evaluated as variable.

const aa = "bb";
const jj = { aa: 4 };
// aa is converted to "aa", not evaluated as variable

console.log(jj.aa === 4);
console.log(jj.bb === undefined);

Computed Property Key, Object Literal Expression

To evaluate a variable as property key, use ES2015 feature, by putting it inside a square bracket.

const aa = "bb";
const jj = { [aa]: 4 };
console.log(jj["bb"] === 4);

[see ES2015 Object Literal Expression Extensions]

Property Symbol Key

Symbol Tutorial

JavaScript Property

BUY
Ξ£JS
JavaScript in Depth

JavaScript in Depth

Basic Syntax

Value Types

Variable

String

Property

Object and Inheritance

Array

Function

Constructor/Class

Iterable 🌟

Misc