We can write without quotes not all object keys, but only those that satisfy the following restrictions: they cannot start with a number and cannot contain a hyphen, a space, or something like that.
If a string violates a constraint, then it must be enclosed in quotation marks. In the following example, part of the keys does not satisfy the conditions, and therefore they are in quotes:
let obj = {'1key': 'a', 'key-2': 'b', key3: 'c'};
Such keys can only be accessed through square brackets:
console.log(obj['1key']);
console.log(obj['key-2']);
Also, accessing such a name through an object property will result in an error:
console.log(obj.1key);
console.log(obj.key-2);
But the third key is valid, and we can access it in both ways:
console.log(obj['key3']);
console.log(obj.key3);
Given an object:
let obj = {
'1a': 1,
'b2': 2,
'с-с': 3,
'd 4': 4,
'e5': 5
};
Which keys of this object require quotes, and which don't?
Fix the errors in the following code:
let obj = {
'1a': 1,
'b2': 2,
'с-с': 3,
'd 4': 4,
'e5': 5
};
console.log(obj.1a);
console.log(obj.b2);
console.log(obj.c-c);
console.log(obj.d 4);
console.log(obj.e5);