Object can have keys only as string or symbol, anything else then these will be converted to string internally.
Object internally converts its keys to string, so 1
and "1"
both are same. So here upperLeft and lowerLeft doesn't throw any error here because it treats them as string only
let obj = {
1: '1',
hey: 'hey'
}
console.log(obj["1"])
console.log(obj[1])
console.log(obj[1] === obj['1'])
The expression in object initialiser are evaluated during initialisation so you can use any expression to have a dynamic key or value.
let key = 'key'
let newKeyValue = "Some value"
const obj = {
[key] : 'some value',
[1 + 2] : 'some more value',
newKey: newKeyValue
}
console.log(obj)
Legal identifiers
means anything which follows the following rules
- Identifier should have only alphabets, numbers, $ and _
- First character should not be number
But in object keys you can use any legal string it will work where as while defining variable you can't use reserved words and illegal identifiers
const obj = {
"1abc" : 'some value'
}
console.log(obj['1abc'])
const do = "no you can't"
Note:- To access invalid identifier you need to use []
bracket notation