JS: Property Key

By Xah Lee. Date: . Last updated: .

JavaScript property key must be strings type or symbol type. Property value can be any type. [see JS: Value Types]

Symbol is a new type in ES2015. [see JS: Symbol Tutorial]

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 oo = {aa:4};   // aa is converted to "aa", not evaluated as variable

console.log( oo.aa === 4 );  // true
console.log( oo.bb === undefined );  // true

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 oo = {[aa]:4};
console.log( oo["bb"] ); // 4

[see JS: ES2015 Object Literal Expression Extensions]

Property Symbol Key

JS: Symbol Tutorial

JS Object Property

  1. Property Overview
  2. Property Key
  3. Dot vs Bracket Notation
  4. Create/Delete Property
  5. Get/Set Property
  6. Check Property Existence
  7. Access Property
  8. List Properties
  9. Property Attributes
  10. Getter/Setter
  11. Property Descriptor
  12. Symbol
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog