7

I tried a few of them,

const obj = {
    '`' : 1,
    '@' : 2,
    '^' : 3,
    '-' : 4,
    '?' : 5,
    ']' : 6,
    '*' : 8,
    ')' : 9,
    '/' : 10,
    '>' : 11,
    'ル': 12
}

console.log(obj); //{ '`': 1, '@': 2, '^': 3,'-': 4, '?': 5, ']': 6, '*': 8, ')': 9, '/': 10, '>': 11, 'ル': 12}

So my question is, what is that superset of characters(individually not a combination of them, which obviously, would be silly to ask) which can qualify as a key in an JavaScript object?

EDITED ---- Definitely not a duplicate! Not sure why is it still marked so! I've had people comparing JSON with JavaScript objects and deriving answers from them. I do understand Which characters are valid/invalid in a JSON key name? has some good insights.

But to touch upon whether a few things are allowed or disallowed wrt comparison between JSON and JavaScript "keys" purely keeping in mind whether those keys are allowed to be typed in or not, how about null, undefined?

I'm not getting into how they are internally coerced and inserted as keys or what coercion takes place while retrieving the value using the brackets [ ] notation. Purely based on whether you are allowed to type in that value or not, yes there is a difference between which keys are allowed in JSON vs what is allowed in JavaScript object.

null as key in JavaScript object

let x = {null: 10};
for(let key in x){
    console.log(key); //null
    console.log(typeof key); //string
}

Works

null as key in JSON

{
    null: 10
}

Doesn't work

Sudhansu Choudhary
  • 3,322
  • 3
  • 19
  • 30

1 Answers1

9

Any string is allowed as an object key. From the spec:

Properties are identified using key values. A property key value is either an ECMAScript String value or a Symbol value. All String and Symbol values, including the empty String, are valid as property keys. A property name is a property key that is a String value.

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
  • 7
    This is absolutely NOT a duplicate - at least it's not a duplicate of ANY answer that references JSON. In addition to using null as a key, what about undefined, true or false? In some languages, you can use arrays or objects as keys, what about those? (I don't think you can do that in JavaScript). It's a legitimate question and has nothing to do with JSON. Sadly, it appears that if you use null, true or false as keys, JavaScript allows it, but converts the value to a string (awful!). So, if you set obj[true] = 42, then you'll find that obj['true'] is set to 42. – John Deighan Feb 20 '22 at 12:49