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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With