JavaScript: Property Names Are Strings

By Xah Lee. Date: . Last updated: .

JavaScript property name are strings. Values can be any type. 〔➤see JavaScript: Data Types

If you have o = {2:7, 3:4}, the keys are still strings, because JavaScript automatically does number to string conversion.

Here's a example.

// property names are strings
o = {"a":7, 2:4}
var k = Object.keys(o);

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

More examples.

var aa = {"3":4, 3:7};
// the second key 3 overrides the first, because property names are strings

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
Like what you read? Buy JavaScript in Depth
or, buy something from my keyboard store