JavaScript: 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 JavaScript: Data Types

Symbol is a new type in ES2015. 〔►see JavaScript: Symbol Tutorial

Property String Key

// property key as string
o = {"a":7, 2:4};
var k = Object.keys(o);

console.log(typeof k[0]); // string
console.log(typeof k[1]); // string

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

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

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

var aa = "bb";

var oo = {aa:4};   // aa is converted to "aa", not evaluated as variable

console.log( oo["aa"] );  // 4
console.log( oo["bb"] );  // undefined

Computed Property Key, Object Literal Expression

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

var aa = "bb";
var oo = {[aa]:4};
console.log( oo["bb"] ); // 4

〔►see JavaScript: ES2015 Object Literal Expression Extensions

Property Symbol Key

JavaScript: Symbol Tutorial

JS Object Property Topic

  1. JavaScript: Property Overview
  2. JavaScript: Property Key
  3. JavaScript: Dot Notation vs Bracket Notation for Properties
  4. JavaScript: Create/Delete Property
  5. JavaScript: Read/Write to Property and Prototype Chain
  6. JavaScript: Check Property Existence
  7. JavaScript: Access Property, List Properties
  8. JavaScript: Property Attributes
  9. JavaScript: Getter/Setter Properties
  10. JavaScript: Property Descriptor
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.