Property Names and Valid Keys
You'll learn which kinds of names you can legally use as keys when defining object properties.
What Can Be a Property Name?
In JavaScript, object property names (keys) are surprisingly flexible. Almost any string can serve as a property name, and JavaScript will automatically convert many identifiers to strings behind the scenes.
When you write an object literal, you typically use simple identifiers:
const person = {
name: "Alice",
age: 30
};
But property names can also be:
- Multi-word strings (requiring quotes):
"first name","user-id" - Numbers (converted to strings):
42becomes"42" - Empty strings:
""is valid - Reserved keywords:
"if","class","return"(when quoted)
The Rules
Unquoted property names follow JavaScript identifier rules: start with a letter, underscore, or dollar sign; contain only letters, digits, underscores, or dollar signs.
const obj = {
validName: 1,
_private: 2,
$special: 3,
name123: 4
};
Quoted property names can contain almost anything: spaces, hyphens, special characters, or reserved words:
const obj = {
"first name": "Alice",
"user-id": 101,
"class": "Advanced",
"": "empty key works!"
};
Numbers are automatically stringified:
const obj = {
42: "answer"
};
// obj["42"] === "answer"
Key Takeaway: Unquoted property names must be valid identifiers, but quoted names can be any string—JavaScript objects are extremely permissive about what you can use as keys.