JavaScript: Property Names Are Strings

, , …,
Want to master JavaScript in a week? Buy Xah JavaScript Tutorial.

JavaScript property name are strings. Values can be any type (string, number, function, object, …).

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.

// demonstration of auto conversion of number to string in property name
var a = {"3":4};               // normal
var b = {3:4};                 // same as {"3":4}
console.log( a["3"] );         // 4
console.log( b[3] );           // 4. The 3 is converted to "3"
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
blog comments powered by Disqus